I draw on the screen a CGContext created using CGBitmapContextCreate and then create a CGImage from it using CGBitmapContextCreateImage and draw it on my view in drawRect (I also draw some others, among other things - this is an exercise to isolate different levels of variability and complexity).
All this works great when everything works on the main thread. However, one of the reasons for splitting this method was that the off-screen part could be launched on the background thread (which, as I thought, should be fine, since it does not appear in the screen context).
However, when I do this, the resulting image is empty! I checked the code and installed a reasonable NSLog to verify that everything is happening in the correct order.
My next step is to reduce this to the simplest code that reproduces the problem (or find some kind of stupid thing that I will miss and fix it) - at this point I would have some code to post here if it is necessary. But at first I wanted to check here that I was not mistaken with this. I could not find anything in my travels around googlesphere that sheds light anyway, but a friend mentioned that he faced a similar problem trying to resize images in the background stream, which suggests that there may be some general limitations.
[edit]
Thanks for the answers so far. If they didn’t tell me anything else, that at least I wasn’t alone without an answer to this, that was part of what I wanted to know. At this point, I am going to add additional work to a simple example and return with some code or additional information. In the meantime, keep any ideas :-)
One moment to educate: a couple of people use the term "thread safety" in relation to the API. It should be noted that in this context there are two types of thread safety:
- The threadability of the API itself - that is, whether it can even be used from more than one thread (global state and other reconnecting problems, such as C strtok, are common reasons why the API may not be too threadful).
- Atomicity of individual operations - can several threads interact with the same objects and resources through the API without blocking the application level?
I suspect the mention so far has been of the first type, but it would be useful if you could clarify.
[edit2 - resolved!]
Well, I did it. The summary is that the problem was with me, not with raster contexts.
In my background thread, just before I delved into the raster context, I was doing some preparation on some other objects. It turns out, indirectly, calls to those other objects, where it leads to the fact that setNeedsDisplay is called on some types! Having separated the part that did this before the main thread, now everything works fine.
So, for those who are faced with this question, I wonder if they can draw in a raster context in the background thread, you can answer (with the reservations that were presented here and in the answers).
Thanks everyone