[clug] pthread coroutines

Andrew Over andrew at cs.anu.edu.au
Mon Feb 9 06:37:19 GMT 2004


On Wed, Jul 02, 2003 at 06:04:49PM +1000, Simon Burton wrote:

> How to use mutexes so that effectively only one out of two threads
> is running at a time? Like co-routines. Each thread blocks on a 
> pthread_mutex_lock() while the other is running. I'm sure it will come to me
> eventually. Or is there Another Way? 

Not quite sure why you want this, but...

... use a mutex and a condition variable?

When you're done doing your work, just go:

  pthread_mutex_lock(&mtx);
  pthread_cond_signal(&cvar);        // Wake up the other thread
  pthread_cond_wait(&cvar, &mtx);    // Now sleep ourselves
  pthread_mutex_unlock(&mtx);

The mutex is only necessary to avoid a race condition (someone calling
wait just as someone else calls signal).  Basically, you initialise
things so that one process waits on the condition variable.  When a
thread has finished doing its thing, it signals to wake up the other
thread, then goes to sleep itself, releasing the mutex and allowing the
other thread to run (since pthread_cond_wait reacquires the mutex before
returning).

I think you could also achieve the same result using two semaphores (one
for each thread).  When done, each thread posts the other, then waits
on its own. 

Cheers,
--Andrew


More information about the linux mailing list