Sign in to follow this  
irreversible

OpenGL and multithreading (shared memory access)

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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):
[code]
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);
}
[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this