Closing ofxThread

Hey hey,

I recently ran into some problems on a project where CloseThread was being called multiple times, causing a crash. I’m still not completely sure how stopThread could be called twice if threadRunning is set to false after being called the first time, but it happened never the less.

When I took a closer look at _thread in ofxThread.h, I noticed that stopThread was being called without closing the thread – stopThread(false). Which means that any later calls to stopThread with arguments set to true wouldn’t actually clear the thread: CloseHandle or pthread_detach would never be called.

This slight adjustment avoided CloseHandle from being called 2x:

  
  
//-------------------------------------------------   
void ofxThread::stopThread(bool close){  
	if(threadRunning){  
		if(close && myThread != NULL){  
			#ifdef TARGET_WIN32  
				CloseHandle(myThread);  
			#else  
				//pthread_mutex_destroy(&myMutex);  
				pthread_detach(myThread);  
			#endif  
		}  
                myThread = NULL;  
		if(verbose)printf("ofxThread: thread stopped\n");  
		threadRunning = false;  
	}else{  
		if(verbose)printf("ofxThread: thread already stopped\n");  
	}  
}  
  
  

… but it doesn’t solve the problem where calling stopThread(true) after stopThread(false) won’t actually clean up the thread resources.

Jeremy

yes, this has happened to me recently with a similar class. it’s super problematic trying to stop and start a thread several times from different threads. you need to lock the access to threadRunning which can lead to dead locks. will look into it.