Reputation: 760
I have two background threads running at the same time. First thread is converting raw pixel data to UIImage (using CGImageCreate) and saves this image into a JPEG using UIImageJPEGRepresentation. Second thread reads JPEG data from a file and loads it into a UIImage. Then the raw pixel data is extracted from this UIImage (using CGBitmapContextCreate).
The problem is that occasionally (1 out of 50) JPEGs the thread writes has corrupted data:
Corrupted image usually has a top/bottom field of solid colour.
The problem goes away if I use a mutex to prevent entire background methods from running at the same time. I've also tried to use libjpeg instead of UIKit methods and it also works fine.
I'm pretty sure my threads never access same image data simultaneously. As far as I know some of the UIKit methods are thread safe. But looks in in this case something is not thread safe.
My question is what would be the right approach to save raw pixel data as JPEG on one thread, while decoding JPEG into raw pixel data on another? I'll also need to do some drawing using UIImage on the main thread at the same time.
Upvotes: 0
Views: 495
Reputation: 760
Turns out the problem was that I deleted the pixel data I passed to CGDataProviderCreateWithData
after creating a CGImage.
The data can only be destroyed after the callback CGDataProviderReleaseDataCallback
is called.
Upvotes: 1