Error when creating window and glfwMakeContextCurrent on separate threads

Started by aerodash, January 22, 2024, 23:33:54

Previous topic - Next topic

aerodash

Hello :)

I am trying to do all rendering on a separate thread.
What I am doing right now is the following:
glfwInit();
long handle = glfwCreateWindow(800, 600, "Demo", NULL, NULL);
new Thread(() -> {
  glfwMakeContextCurrent(handle);
  GL.createCapabilities();

  int shader = loadShaders();
  int vao = createVao();

  while (!glfwWindowShouldClose(handle)) {
    glUseProgram(shader);
    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glfwSwapBuffers(handle);
    glfwPollEvents();
  }
}).start();


With the above code, rendering works as I can see a triangle but the window is not responsive.
When moving or clicking on the window the process would stop responding.

spasi

Hey aerodash,

Please see https://github.com/LWJGL/lwjgl3/blob/master/modules/samples/src/test/java/org/lwjgl/demo/stb/Vorbis.java for a working example of multithreaded UI (i.e. the event loop), rendering and audio.

The recommended approach is to use the main thread for the event loop (with glfwWaitEvents) so that you're always consuming UI events, then spawn secondary thread(s) for rendering and audio. This works nicely on macOS too (where the event loop must always be on the first thread of the process). Rendering never stops, even while dragging the window.

aerodash

Hello Spasi :)

Thank you very much.
That worked great !
Just added this:
while (!glfwWindowShouldClose(handle)) glfwWaitEvents();