Re: Threading question (avoiding deadlock)



>I was hoping somebody could point me in the right direction here.

your periodic update thread should check a variable that tells it to
die. add a lock and a condition variable, and use it like this:

void
kill_periodic_thread ()
{
	pthread_mutex_lock(&lock_protecting_kill_flag);
	kill_flag = TRUE;
	pthread_cond_wait (&periodic_is_dead, &lock_protecting_kill_flag);
	/* at this point we know that barring a segfault,
	   the periodic thread is going to exit.
	 */
	pthread_mutex_unlock(&lock_protecting_kill_flag);
	pthread_join(); 
}

void *
periodic_thread (void *arg)
{
	while (!kill_flag) {
            .... do stuff ....
        }			   

	if (kill_flag) {
	    ... clean up ...
	    pthread_mutex_lock (&lock_protecting_kill_flag);
	    pthread_cond_signal (&periodic_is_dead);
	    pthread_mutex_unlock (&lock_protecting_kill_flag);
	    pthread_exit ();
        }	    
	...
}

note: you don't really to need to lock before checking kill_flag on
most architectures, but you might prefer:

        pthread_mutex_lock (&lock_protecting_kill_flag);
	if (kill_flag) {
	    ... clean up ...
	    pthread_cond_signal (&periodic_is_dead);
	    pthread_mutex_unlock (&lock_protecting_kill_flag);
	    pthread_exit ();
        }	    
        pthread_mutex_unlock (&lock_protecting_kill_flag);


if you want to be more formal. you might also be able to get away
without the condition variable, and just use:

	kill_flag = TRUE;
	pthread_join (...);

although this becomes harder to debug under some circumstances.

--p






[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]