Wednesday, October 27, 2010

Multithreading in OpenGL.

Tip - Since OpenGL maintains unique resource ID for each thread some special handling is required to use OpenGL in a multithread enviornment.

Details - In OpenGL we should have seperate context for each thread. And each context will keep seperate IDs for the resources created in its thread. Due to this the resources made in one thread will not be accessible in another thread. To avoid this limitation the contexts of the threads that we wish should be shared using the call wglShareLists. It should be cared that the context of the threads that we wish to share, shoud be shared before we make them the current context of individual threads. A simple example is given below.

Suppose we need to use OpenGL resources in Thread1 and Thread2.

unsigned int Thread1(LPVOID lpParam)
{
    HGLRC hThread1Context = wglCreateContext( hDC ); // hDC is the device context to which drawings should be done.
    HGLRC hThread2Context = wglCreateContext( hDC );
    // Share the context
   wglShareLists( hThread1Context, hThread2Context );
   wglMakeCurrent( hDC_i, hThread1Context )
}

unsigned int Thread2(LPVOID lpParam)
{
   wglMakeCurrent( hDC_i, hThread2Context )
}

Note:- It is seen that the CPU utilisation of the rendering applications goes higher when we share the contexts which uses same window DC for rendering. To avoid this issue it is recommended not to share contexts of the threads which uses same window. 

Posted By : Xavier K Joseph

No comments:

Post a Comment