c++ - 如何多线程glfw键盘回调?

标签 c++ multithreading opengl glfw

我正在创建一个 opengl 应用程序,当我不使用多线程时它运行良好。原代码如下所示:

void Controller::BeginLoop()    
{    
    while (!glfwWindowShouldClose(_windowHandle)) {    
        /* Render here */     
        Render();    

        /* Swap front and back buffers */     
        glfwSwapBuffers(_windowHandle);

        /* Poll for and process events */     
        glfwPollEvents(); 
    }     
}    

int main()
{
    //do some initialization
    g_controller->BeginLoop();
}

上面的代码运行良好,但是,当我尝试将事件轮询和渲染放入两个不同的线程时,OpenGL 不会在窗口中绘制任何东西。下面是我使用的多线程代码:

void Controller::BeginLoop()    
{    
    while (!glfwWindowShouldClose(_windowHandle)) {  

        glfwMakeContextCurrent(_windowHandle);

        /* Render here */     
        Render();    

        /* Swap front and back buffers */     
        glfwSwapBuffers(_windowHandle);
    }     
}    



void Render(int argc, char **argv)
{
    ::g_controller->BeginLoop();
}

int main()
{

    std::thread renderThread(Render, argc, argv);

    while (true) {
        glfwPollEvents();
    }

    renderThread.join();

    return 0;
}

在 Render 函数中,我做了一些物理并将结果点绘制到窗口上。 我完全不知道出了什么问题。

最佳答案

创建 GLFW 窗口后,由此创建的 OpenGL 上下文将在创建窗口的线程中成为当前线程。在使 OpenGL 上下文在另一个线程中成为当前上下文之前,必须在当前持有它的线程中释放(使其成为非当前)。因此,持有上下文的线程必须在新线程调用 glfwMakeCurrent(windowHandle) 之前调用 glfwMakeContextCurrent(NULL) – 在启动新线程之前或通过使用同步对象(互斥量、信号量)。


顺便说一句:以下划线 _ 开头的符号在全局命名空间中为编译器保留,因此要么确保 _windowHandle 是类成员变量,要么仅使用带下划线的符号函数参数。

关于c++ - 如何多线程glfw键盘回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30431929/

相关文章:

iphone - 如何在iPhone屏幕上用线条画签名?

c++ - 为什么类不能继承其父类的成员类型?

c++ - 导入位图使我的窗口滞后

java - 控制线程的不同实例

python - 如何在Python中将多个摄像机源流传输到单个套接字

c++ - 使球相互反弹(openGL)

opengl - texelFetch 的替代品?

c++ - boost asio 中的并发读取和 async_read_some

c++ - Cmake 外部资源

c# - 每隔几分钟在 global.asax 中执行一次方法