学习apue11.6.6 condition variables实践:
使用书上的condition variables和wait函数
1 #include<pthread.h>
2 #include<stdio.h>
3 #include<iostream>
4
5 using namespace std;
6
7 bool flag = false;
8 pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
9 pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
10 void * printid(void *i)
11 {
12
pthread_mutex_lock(&qlock);
13
while(!flag)
14
pthread_cond_wait(&qready,&qlock);
15
printf("thread id is : %lu\n",(unsigned long)pthread_self());
16
//return ((void *)0);
17
pthread_mutex_unlock(&qlock);
18
pthread_exit((void *)1);
19 }
20 void go()
21 {
22
pthread_mutex_lock(&qlock);
23
flag = true;
24
pthread_mutex_unlock(&qlock);
25
pthread_cond_signal(&qready); // 第一种结果
//pthread_cond_broadcast(&qready); //第二种结果
26 }
27 pthread_t ths[10];
28 int main()
29 {
30
31
for(int i = 0;i<10;++i){
32
pthread_create(&ths[i],NULL,printid,NULL);
33 }
34 go();
35
for(int i=0;i<10;++i){
36
pthread_join(ths[i],NULL);
37 }
38
exit(0);
39 }