等待条件有两种方式:无条件等待pthread_cond_wait()和计时等待pthread_cond_timedwait()
激发条件有两种形式:pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;而pthread_cond_broadcast()则激活所有等待线程
在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。
在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应
用互斥量锁住条件,防止同一个条件被多个线程竞争.
下面例子是创建三个线程,设定全局变量i,当i==1时唤醒线程1,当i==2时唤醒线程2,当i==3时唤醒线程3.
#include <stdio.h> #include <unistd.h> #include <pthread.h> int i = -1; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition = PTHREAD_COND_INITIALIZER; void thread1() { printf("Therad1 Begin\n"); pthread_mutex_lock(&mutex); while (i != 1) { printf("Therad1 Waiting\n"); pthread_cond_wait(&condition, &mutex); } printf("Thread1 doing\n"); pthread_mutex_unlock(&mutex); printf("Thread1 End\n"); } void thread2() { printf("Therad2 Begin\n"); pthread_mutex_lock(&mutex); while (i != 2) { printf("Therad2 Waiting\n"); pthread_cond_wait(&condition, &mutex); } printf("Thread2 doing\n"); pthread_mutex_unlock(&mutex); printf("Thread2 End\n"); } void thread3() { printf("Therad3 Begin\n"); pthread_mutex_lock(&mutex); while (i != 3) { printf("Therad3 Waiting\n"); pthread_cond_wait(&condition, &mutex); } printf("Thread3 doing\n"); pthread_mutex_unlock(&mutex); printf("Thread3 End\n"); } int main(int argc, const char * argv[]) { pthread_t tid1; pthread_t tid2; pthread_t tid3; void *t1 = thread1; void *t2 = thread2; void *t3 = thread3; pthread_create(&tid1, NULL, t1, NULL); pthread_create(&tid2, NULL, t2, NULL); pthread_create(&tid3, NULL, t3, NULL); while (i != 3) { i++; printf("i = %d\n",i); sleep(3); pthread_cond_broadcast(&condition); } return 0; }
输出结果:
i = 0 Therad1 Begin Therad1 Waiting Therad3 Begin Therad2 Begin Therad3 Waiting Therad2 Waiting i = 1 Thread1 doing Thread1 End Therad3 Waiting Therad2 Waiting i = 2 Therad3 Waiting Thread2 doing Thread2 End i = 3 Thread3 doing Thread3 End
总结:条件不满足时,线程挂起,等待条件满足.
因为使用的pthread_cond_broadcast,所以使用while循环判断条件是否成立.
当没有用互斥量锁住条件时:
i = 0 Therad3 Begin Therad1 Begin Therad2 Begin Therad3 Waiting Therad1 Waiting Therad2 Waiting i = 1 Therad3 Waiting Therad2 Waiting Thread1 doing Thread1 End i = 2 i = 3//////////////或者/////////////i = 0Therad1 BeginTherad3 BeginTherad2 BeginTherad1 WaitingTherad3 WaitingTherad2 Waitingi = 1Thread1 doingThread1 Endi = 2i = 3
时间: 2024-11-03 22:09:20