How to multithreading glfw keyboard callback?
Asked Answered
C

1

5

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.

Condense answered 25/5, 2015 at 5:47 Comment(0)
T
7

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.

Tepper answered 25/5, 2015 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.