Creating OpenGL structures in a multithreaded program?

后端 未结 2 1218
独厮守ぢ
独厮守ぢ 2021-01-01 19:57

I am attempting to do the following in a physics engine I am building:

Have 2 threads, one for world logic, one for rendering.

The main thread (the thread fr

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 20:35

    The requirement for OpenGL is that the context created for rendering should be owned by single thread at any given point and the thread that owns context should make it current and then call any gl related function. If you do that without owning and making context current then you get segmentation faults. By default the context will be current for the main thread. So to make your program multi threaded you have two options.

    1. Create two contexts and share resources like texture objects VAOs between them.Advantage of this approach is you can refer in thread 2 to any VAO created in thread 1 and it wont crash.

      Thread_1:

      glrc1=wglCreateContext(dc);
      
      glrc2=wglCreateContext(dc);
      
      BOOL error=wglShareLists(glrc1, glrc2);
      
      if(error == FALSE)
      {
      
      //Unable to share contexts so delete context and safe return 
      
      }
      
      wglMakeCurrent(dc, glrc1);
      
      DoWork();
      

      Thread_2:

      wglMakeCurrent(dc, glrc2);
      
      DoWork();
      
    2. Other option is to make one context per thread and make it current when thread starts. Like following

      Thread_1:

      wglMakeCurrent(NULL, NULL);
      
      WaitForThread2(); OrDoSomeCPUJob();
      
      wglMakeCurrent(dc, glrc);
      

      Thread_2:

      wglMakeCurrent(dc, glrc);
      
      DoSome_GL_Work();
      
      wglMakeCurrent(NULL, NULL);
      

    Hope this clears up the thing.

提交回复
热议问题