OpenGL and multithreading (shared memory access)

Started by
1 comment, last by Erik Rufelt 12 years, 11 months ago
This is a memory management question and I'm not sure what the precise problem is since I've assumed thus far all process threads effectively share a common memory space as far as access is involved. This is what I have:

BYTE* data = NULL;

//worker thread
workerthreadrpoc()
{
data = LoadImage();
}

//main thread
updategl()
{
//calls all regular GL functions, eg glGenTextures, etc; also crashes when I pass data to it that is allocated in a worker thread
if(data) LoadGLTexture(data);
}

//main thread
mainloop()
{
updategl();
}

I'm well aware of GL and D3D's multithreading issues on driver level and I'm not trying to do anything like that, but I wasn't aware I couldn't pass system memory pointers to GL from different threads in the same process. Something simple like copying the data loaded in a worker thread to a buffer allocated in the main thread naturally avoids the problem, but I'm pretty sure that's a silly solution and locking the memory or mapping it to the current thread or what not does the same thing more effectively. Bottom line is, I'm on Windows and I don't know how to do that :).

So if anyone could point me to the appropriate API's or a good article I'd be really grateful! It's funny how googling something like "multithreading shared memory winapi" can turn up so little concrete and useful information.
Advertisement
Your code should work fine. Just make sure memory to what global data pointer points doesn't get changed/invalidated/corrupted during LoadGLTexture function call.
If everything is loaded properly that works fine. Make sure you use critical sections, and make sure you know who is supposed to delete the data and when.

Something like this in the most basic form (there are smarter ways to structure it):

volatile byte *data = 0;
CRITICAL_SECTION cs;

void loadThread() {
char *localData = new [...];
loadImage(..);

// Only do this once loading is complete and the memory won't be touched here again
EnterCriticalSection(&cs);
data = localData;
LeaveCriticalSection(&cs);
}

void glThread() {
while(..) {
EnterCriticalSection(&cs);
if(data) {
glBufferData(..., data);

// Assuming this thread is now supposed to own the data
delete[] data;
}
LeaveCriticalSection(&cs);
}
}

void init() {
InitializeCriticalSection(&cs);

CreateThread(.., loadThread);

glThread();

DeleteCriticalSection(&cs);
}

This topic is closed to new replies.

Advertisement