PDA

View Full Version : Running GlutMainLoop from separate thread


davidl
2004.10.04, 09:39 AM
Hi

I've made a cross platform application running OpenGL through glut. When porting it to mac the window stopped to respond to mouse clicks and repaint events.

This piece of code shows the error (tested on MacOS 10.3). If undefining THREADED it will work properly.

// GLUT problem
// Build with g++ -framework GLUT -framework OpenGL -framework Foundation -o pthglut *.cpp

#include <iostream>
#include <pthread.h>
#include <GLUT/glut.h>

void display(){
glClear(GL_COLOR_BUFFER_BIT);
glutSwapBuffers();
}

void menuFunc(int i){
exit(0);
}


static void* glutThreadFunc(void* v){
int argc = 1;
char *argv[] = {"x"};
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowPosition(100, 100);
glutInitWindowSize(320, 240);
glutCreateWindow("pthglut!!111!");
glutDisplayFunc(display);
int glmenu = glutCreateMenu(menuFunc);
glutAddMenuEntry("Quit", 1);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
}

#define THREADED

int main(){
pthread_t glutThreadId;
#ifdef THREADED
pthread_create(&glutThreadId, NULL, glutThreadFunc, 0);
while(true){
sleep(100);
}
#else
glutThreadFunc(0);
#endif
}

Does anyone know what's going on and if it's possible to fix it?

/David L

arekkusu
2004.10.04, 10:48 AM
GLUT on OS X is built on top of Cocoa and AppKit. Some portions of AppKit (event handling and window drawing) aren't reentrant and must be called from the main thread.

You can still use threads in GLUT apps, just keep the main loop in the main thread and put your computational stuff in secondary thread(s). I've done that and it works OK.