work with several contexts from different threads

Is it possible to work with several GL contexts from different threads within process?
Each thread has it’s own window and context.
The apllication crashes somewhere in the NV driver by fact.
Maybe some flags is required or is it necessary to wrap every GL call in critical section?

Well if you don’t use a critical section, another thread might change the current context in the middle of the rendering of your current thread, so I guess you should do something like this in all your rendering threads:


Lock gl mutex
Make context current
Issue gl commands
Unlock gl mutex

No, there is no need for crit.sections.
Be sure you properly init the OpenGL in each thread. One context can only be active in one thread.

FYI, if you have one GPU, the multithreading in opengl does not increase performance (usually the opposite).

From my experience the best way to use multiple gl contexts (even with sharing) between multiple threads is to:

  1. In main thread create N gl contexts that you need, but DO NOT MAKE THEM CURRENT.
  2. Start N threads and pass one RC per each thread.
  3. Inside thread’s worker function, call wglMakeCurrent once at beggining and the use context as usuall.

Few years ago I did some tests with OpenGL UI elements. The problem was how to decuople OpenGL UI rendering from scene rendering… If scene is too complex, UI start lagging.
So I create 3 GL contexts… first for scene rendering, second for UI rendering and third as muxer.

  1. scene rendering contex have infinite update+render loop. Scene was rendererd in FBO
  2. UI rendering thread perform update&render only on some event. UI is also rendererd in FBO
  3. mixer have fixed FPS (60) and it use shared textres from first two contexts mix them and render on screen.

During development of that test I tried everything to achive proper multiple thread & contexts rendering and resource sharing.

1 Like