int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
等待条件有两种方式:条件等待pthread_cond_wait()和计时等待pthread_cond_timedwait(),其中计时等待方式如果在给定时刻前条件没有满足,则返回ETIMEDOUT,结束等待,其中abstime以与time()系统调用相同意义的绝对时间形式出现,0表示格林尼治时间1970年1月1日0时0分0秒。
无论哪种等待方式,都必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的竞争条件(Race Condition)。mutex互斥锁必须是普通锁(PTHREAD_MUTEX_TIMED_NP)或者适应锁(PTHREAD_MUTEX_ADAPTIVE_NP),且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应。
int pthread_cond_signal(pthread_cond_t *cond)
int pthread_cond_broadcast(pthread_cond_t *cond)
激发条件有两种形式,pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;而pthread_cond_broadcast()则激活所有等待线程。
#include <unistd.h> #include <pthread.h> #include <stdio.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void* thread_1(void *a) { while(1) { pthread_mutex_lock(&lock); pthread_cond_wait(&cond, &lock); printf("1111111111111\n"); pthread_mutex_unlock(&lock); sleep(1); } } void* thread_2(void *a) { while(1) { pthread_mutex_lock(&lock); printf("222222222\n"); pthread_mutex_unlock(&lock); pthread_cond_signal(&cond); sleep(2); } } void* thread_3(void *a) { while(1) { pthread_mutex_lock(&mutex); printf("333333333\n"); pthread_mutex_unlock(&mutex); sleep(3); } } void* thread_4(void *a) { while(1) { pthread_mutex_lock(&mutex); printf("222222222\n"); pthread_mutex_unlock(&mutex); sleep(4); } } int main() { int i; pthread_t ths[2]; #if 1 pthread_create(&ths[0], NULL, thread_1, 0); pthread_create(&ths[1], NULL, thread_2, 0); #else //pthread_create(&ths[0], NULL, thread_3, 0); //pthread_create(&ths[1], NULL, thread_4, 0); #endif for(i = 0; i < 2; ++ i){ pthread_join(ths[i], NULL); } printf("Play End!\n"); return 0; }