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;Thread 1 - wait until x>y
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_lock(&mut);
while (x <= y) { pthread_cond_wait(&cond, &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);
- mutex mut protects variables x and y.
- pthread_cond_wait will unlock mut and go to sleep and waits for the condition variable cond to be signalled.
- thread 2 signal cond by calling pthread_cond_signal or pthread_cond_broadcast
沒有留言:
張貼留言