I'm having trouble getting opengl to work in multiple threads on windows. I followed the sample code from the opengl wiki but Its simply not working for me.
I tried to generate and build a display list on my main thread and within the other thread, both with the same opengl configuration (2 contexts sharing lists). When on the main thread it works perfectly. When on the separate thread, it generates the id but seems to ignore all the commands associated with actually building the list.
I've monitored the processes memory usage during both trials and it is clear that the display list is never generated when called to do so in the other thread.
I've encountered this problem before and gave up on multi-threading opengl, I really want to get it to work this time. Any help is appreciated.
Here is the related code:
DWORD WINAPI Windows::thread_callback(void* arg)
{
Windows* window = static_cast<Windows*> (arg);
wglMakeCurrent(window->hdc, window->thd_hrc);
while (!window->done)
window->ThreadLoop();
if (!wglMakeCurrent(0,0))
error("Could not Thread context", "", "Shutdown Error").print();
if (!wglDeleteContext(window->thd_hrc))
error("Could not delete thread context", "", "Shutdown Error").print();
}
// During Window creation...
if (!(hdc=GetDC(hwd)) ||
!(PixelFormat=ChoosePixelFormat(hdc,&pfd)) ||
!(SetPixelFormat(hdc,PixelFormat,&pfd)) ||
!(hrc=wglCreateContext(hdc)) ||
!(thd_hrc=wglCreateContext(hdc)) )
{
destroy_window();
return false;
}
You can use OpenGL on different contexts (with shared lists) simultaneously on multiple threads. This works for me:
#include <windows.h>
#include <gl/gl.h>
// This thread uses the first context
wglMakeCurrent(hDC, hGLRC);
// List id
GLuint listId = glGenLists(1);
// Create the thread that will use the second context to update the display-list
ThreadData data;
data.exitNow = false;
data.hDC = hDC;
data.hGLRC = hGLRCThread;
data.listId = listId;
Note however that the actual synchronization is up to the driver, and if your thread tasks aren't CPU heavy it might not help a lot. For example, when I try updating a very large texture on a shared context in a separate thread, my main thread still gets stalled. This is probably because data upload to the graphics card is not possible during operation, either in the hardware or in the driver. Updating the large texture in 256x256 tiles one at a time however yields very good results, but these could just as well have been executed on the main thread after a separate thread had done all CPU calculations preparing the texture.
However, if multiple shared contexts fits better, you should definitely be able to use that as long as you properly set up the sharing.