Macos – How to use GLUT not in main thread on OS X

glutmacosopengl

I once tried to open a GLUT window from a sub-thread and got lots of nasty problems. I remember this post on lists.apple.com:

GLUT functions may only be called from the application's main thread

Has anything changed in this regard with GLUT on Mac OS X ? Is there a thread-safe GLUT that let's you open windows from any thread ?

If GLUT is not an option, is there a tiny library that replaces GLUT and would work from any thread ?

[edit]

Here is the result of my tests triggered by the various solutions proposed as answers:

  • GLFW looked nice but did not compile (current branch is 3 years old)
  • Agar was another pretender but it's too big for the tiny need I had
  • SDL is not BSD-license compatible and it's a huge library for code that should fit on a single file
  • GLUT cannot run in any thread.

I decided to reinvent the wheel (yes, that's good sometimes) and the final class is just 200 lines of code. It let's me open and close a window from any thread (openGL draw in new thread) and I have full control on vertical sync and such (SDL uses double buffering = slow for openGL). I had to trick around the NSApp to properly start and stop the application (which does not use an event loop otherwise).

To those telling me that OpenGL is not thread-safe, that's not exactly true: you can run multiple OpenGL threads and the draw commands will be executed in the OpenGL state assigned to that thread. OpenGL is thread-specific.

If anyone needs some bare-bones code to create OpenGL windows using Cocoa: gl_window.mm

Best Answer

GLUT is not thread safe. You'll need locking primitives with whatever solution you choose to implement. I'd recommend setting up your own GL view in Cocoa and rewriting the plumbing that GLUT provides.

Take a look at SDL as a modern GLUT replacement. It should give you all the cross-platform you want. As far a cross-platform threading, Boost provides a portable library.

Related Topic