Search code examples
pthreadsglfw

What makes a pthread the "main" thread?


What makes a pthread the "main thread"?

I'm asking because some GLFW functions must only be called from the main thread. I understand the concept of thread safety. But what is special about the main thread? Why can't I run all GLFW functions from a non-main thread?


Solution

  • What makes a pthread the "main thread"?

    In a POSIX environment (where you would find pthreads), the term usually means the initial thread of the program, in which the (first) entry into main() occurs. That is how the GLFW documentation uses it.

    But what is special about the main thread?

    Pthreads itself does not specially distinguish a program's initial thread. The initial call to main() within is distinguished by the fact that returning from that call terminates the whole program, but that's not what GLFW is interested in. The docs explain:

    Initialization, termination, event processing and the creation and destruction of windows, cursors and OpenGL and OpenGL ES contexts are all restricted to the main thread due to limitations of one or several platforms.

    (Emphasis added)

    It seems that GLFW's "one or several platforms" mostly means MacOS, though Windows and X11 each have their own idiosyncrasies that play in this area. GLFW says "Screw all that. It works everywhere to restrict most operations to the main thread, so that's what we're going to require." That makes it easier for them and for you the application programmer.

    Why can't I run all GLFW functions from a non-main thread?

    Because GLFW aims to be cross-platform, and that doesn't work on MacOS. If you mean why can't you call GLFW functions from arbitrary threads then that also doesn't, in general, work on Windows. If you mean you want to designate a specific thread on which all GLFW operations will be performed then that could in principle be done on both Windows and Unix, but then why not choose the main thread? Putting your GUI event loop in the main thread is pretty standard.