Invalid OpenGL context inside framebuffer size callback in multithreaded application

Hi everyone! I’m writing this post to see if somebody can help me solve a problem that I have been looking at for a few days. Here’s the situation:

  • I have an application with two threads.
  • In the main thread I initialize GLFW, create a window, set the framebuffer size callback, call gladLoadGLLoader and at the end I call glfwMakeContextCurrent(nullptr). After that, the main thread never does anything related to GLFW or OpenGL again.
  • In the second thread I first call glfwMakeContextCurrent with the window that was created in the main thread and then I make all my OpenGL calls to render.

With this setup everything works perfectly except for one thing: when I resize my window, the framebuffer size callback is executed as expected, but the call to glViewport inside of it results in a GL_INVALID_OPERATION error.

I believe this is happening because the framebuffer size callback is executed in the main thread, which does not own the OpenGL context. One solution would be to simply store the new dimensions of the framebuffer when the callback is executed, and to call glViewport at the beginning of every iteration of the render loop in the second thread. The problem with this, however, is that I also need to resize some framebuffers that I created myself when the window is resized. Doing this in every iteration of the render loop doesn’t give me the results I want.

I read this other post about a setup that is very similar to mine, but none of the answers cover the problem I’m trying to solve.

So my question is: is there a way to give the OpenGL context to the main thread when the framebuffer size callback is executed?

Thank you for any information!

I would not make the context current on the main thread. Instead I would record the new viewport parameters somewhere in data, and pass that to the secondary thread so that it can call glViewport at the beginning of it’s rendering.