Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multithreading glfw keyboard callback?

I am creating an opengl application and it works well when I didn't use multithreading. The original code is shown below:

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();
}

The above code works well, however, when I tried to put the eventpolling and rendering into two different threads, the OpenGL won't draw anything in the window. Below is the multithread code I used:

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;
}

In the Render function, I do some physics and draw the result points onto the window. I totally have no idea what is going wrong.

like image 542
n3v3rm03 Avatar asked May 25 '15 05:05

n3v3rm03


1 Answers

After creating a GLFW window the OpenGL context created by this will be made current in the thread that did create the window. Before you can make an OpenGL context current in another thread is must be release (made un-current) in the thread currently holding it. So the thread holding the context must call glfwMakeContextCurrent(NULL) before the new thread is calling glfwMakeCurrent(windowHandle) – either before launching the new thread or by using a synchronization object (mutex, semaphore).


BTW: Symbols starting with an underscore _ are reserved for the compiler on the global namespace, so either make sure _windowHandle is a class member variable or use underscored symbols only for function parameters.

like image 147
datenwolf Avatar answered Nov 02 '22 06:11

datenwolf