0
votes

I'm building an app for Mac OS 10.6 that will use OpenGL. I'd like to offshore the rendering to a secondary dispatch queue (instead of the main thread).

From what I understand, I need to use a thread-local OpenGL context to do my graphics work. My plan is to acquire a reference to it on my first block, then reuse the same instance over and over again.

However, dispatch queues and threads aren't the same, and the debugger of Xcode 4 shows that a queue can use several threads. Therefore, I'm not sure if what I'm doing is safe (even though I believe that only parallel queues can use several threads).

Is there a guarantee that all blocks sent to a serial queue are sent to the same thread? Should I instead get the current OpenGL context and assign it to my NSOpenGLView at each frame?

4

4 Answers

1
votes

You don't need a separate OpenGL context for each thread. But a OpenGL context must be active in only one thread at a time. So what you could do is making the context active when entering a worklet, and deactivating it when leaving.

However multithreaded use of OpenGL usually reduces perfomance. There's litte what can be parallized from the OpenGL API caller's side, anyway, as the order of operations is very important. The GPU however will perfectly parallelize all operations.

So I suggest to keep all OpenGL operations in a single thread, and use working queues for things like I/O, user interaction, sound, simulation, etc.

1
votes

Queues are not bound to any specific thread of execution

There is no guarantee that all blocks sent to a serial queue are sent to the same thread. You need to use main queue for rendering or to implement for queueing blocks on threads with GL context using NSThread or pthread as main queue.

1
votes

There is some more specific info on OpenGL with GCD here:

http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/ConcurrencyandOpenGLES/ConcurrencyandOpenGLES.html

GCD and NSOperationQueue objects can execute your tasks on a thread of their choosing. They may create a thread specifically for that task, or they may reuse an existing thread. But in either case, you cannot guarantee which thread executes the task. For an OpenGL ES application, that means:

  • Each task must set the context before executing any OpenGL ES commands.
  • Your application must ensure that two tasks that access the same context are not allowed to execute concurrently.
  • Each task should clear the context before exiting.
0
votes

Nope, sorry, there is no guarantee.