pthreads and glut...

I am writing simple program in C++ using glut to manage my opengl windows, and I would like to start a new thread for the glutMainLoop, so that my main program can continue running as usual after starting glut. My problem is that when I spawn a new thread for glutMainLoop, I can’t see any new windows being created, and my redrawing methods are never being called. They print output as well as drawing, I never see this output. However, if I replace the pthread_create with a direct call to glutMainLoop(), the window will appear, and the redraw methods are called appropriately. My pthread create code is okay, I put a printf right before the call to glutMainLoop, inside the new thread, and I see that message. I also know that glutMainLoop is not returning. What is it doing other than drawing my window?

here is the relevant code:

 
//i call the thread like this:
pthread_create(&glutThread,&glutThreadAttributes,
     mainLoopThread,NULL);


//and the functions that it spawns are these:
void mainLoopOnce(){
	cout<<"Starting glutMainLoop
";
	fflush(stdout);
	glutMainLoop();
	cout<<"Glut main loop returned!
";
	fflush(stdout);
}

void *mainLoopThread ( void* a ){
	pthread_once(&glutMainLoopOnce, 
              mainLoopOnce);
	return NULL;
}
  

I’m not sure, but maybe it’s because glutMainLoop is in another thread so it can’t find a valid gl context. I’m also not sure if glut can be used with threads. After all it was created as a basic simple api. I don’t know if they address threads in OpenGLUT. Might be worth taking a look.

Try to do all the glut function calls inside your thread so you ensure all glut calls match the same context.