星期六, 9月 09, 2006

Pthread conditional wait

When writing multi-thread program, you may want to wait until another thread finished to continue the current thread. You can use pthread_join after a thread has been created.

int retm=pthread_create(&main_thread,NULL,init_gtk_thread,(void *)0);
pthread_join(main_thread,NULL);

The current thread will be blocked until main_thread finished by calling pthread_exit or return.

But when you want to wait until some condition met, you will need to use a condition variable and a mutex .

Example

int x,y;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
Thread 1 - wait until x>y
pthread_mutex_lock(&mut);
while (x <= y) { pthread_cond_wait(&cond, &amp;mut); } /* operate on x and y */ pthread_mutex_unlock(&mut);
Thread 2 - modify x and y
pthread_mutex_lock(&mut);
while(x<=y)x++; if (x > y) pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mut);

  1. mutex mut protects variables x and y.
  2. pthread_cond_wait will unlock mut and go to sleep and waits for the condition variable cond to be signalled.
  3. thread 2 signal cond by calling pthread_cond_signal or pthread_cond_broadcast
P.S. Pthread-win32 is here

沒有留言: