Reputation: 1728
This is my current setup: I'm doing OpenGL rendering using SDL (currently on Linux). I initialize SDL (SDL_Init
) and create the application window (SDL_CreateWindow
) in the main thread and pass it to a second thread. This second thread creates an OpenGL context from it (SDL_GL_CreateContext
) and starts a render loop, while the main thread listens for events. I think it's important to note that GL calls are completely confined to this second thread; actually most of my application logic happens there, the main thread is really only responsible for handling events that come in over SDL.
Originally I did this the other way around, but it turns out you can't process events in anything other than the main thread on OSX and probably also Windows, so I switched it around to be compatible those two in the future.
Should I have any concerns that this will not work on OSX/Windows? On Linux, I haven't had any whatsoever. There's lots of information on the internet about context sharing and doing GL calls from multiple threads, but all I want to do is do OpenGL in one thread that is not the main one. I wouldn't like to continue coding my application only to later find out that it won't work anywhere else.
Upvotes: 21
Views: 6905
Reputation: 99
OpenGL and multithreading are basically enemies : only one thread can 'own the render context' at any given moment - yes, you can switch the GL render context whenever threads switch, but think of the cost, and also consider that, from one OEM driver to the next, it's not well supported and likely to work for some people and not others. The only logical (and sane) alternative, is to keep all your OpenGL calls to one thread (note: there are exceptions, there are things that any thread can call in gl, relating to streaming data, without them needing to own render context). Unfortunately, we can't simply pass the GL context around threads as suggested, we must call (w)glMakeCurrent, which tells GL "this caller thread now owns you", but fails to tell other threads that...
Upvotes: 1
Reputation: 6440
I have an app which runs on Mac/iOS/Windows that is structured this way (all GL in a rendering thread), but I don't use SDL.
I just took a look at SDL's Cocoa_GL_CreateContext
(called by SDL_GL_CreateContext
on OS X) and it makes calls that I make from my main thread to set up the context.
So, if you hit any problems, try creating the GL context in the main thread and then pass that off to the rendering thread (instead of creating the GL context in the rendering thread).
Upvotes: 4