PDA

View Full Version : Quick threaded OpenGL drawing question in Cocoa


TomorrowPlusX
2004.11.10, 10:54 AM
I recently adapted my game engine to use a separate thread ( a pthread, not NSThread ) to run the physics as opposed to a timer, and I saw a fair decline in CPU use ( about 8 to 10% ), which is very encouraging. So I'm considering using a thread to schedule display.

That said, I'm aware that on OS X any calls to OpenGL must be made from the same thread as which created the context.

So, my question is, does calling display on an NSOpenGLView draw the view directly in the caller's thread, or enqueue an event to the application object to redisplay in the app thread?

I could write a test to verify, but it would take time and I figure somebody here's got to know ;)

Thanks?

arekkusu
2004.11.10, 04:42 PM
I'm aware that on OS X any calls to OpenGL must be made from the same thread as which created the context.
Not true. You can create a context and then draw into it from any number of threads. The trick is that a context is a shared resource; only one thread can be drawing into it at a time, and that includes the window manager resize/move/minimize etc via the main thread.

So for multithreading:
* acquire a lock in your rendering methods (drawRect, reshape...) to prevent simultaneous access
* make sure the context is current before submitting any commands.

Failing to do both of these results in either no gfx, garbage, or a hung system (because the GL drivers are kernel extensions. If you render from multiple threads into one context simultaneously the command streams is corrupted, your computer goes boom.)

TomorrowPlusX
2004.11.11, 08:23 AM
That sounds fairly complicated. Fortunately, I don't need to worry about it now. I've changed my timer to have a time interval of zero, and I'm letting the vblank sync keep it managed. With the physics running independently at 100htz, the game runs smoothly regardless of the current fps.

Thanks for the note, though.