#i nclude
#i nclude
#i nclude <pthread.h>
#i nclude
using namespace std;
pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
int counter =0;
int estatus=-1;
void * decrement_count(void * argv);
void * increment_count(void * argv);
int main(int argc, char *argv[])
{
printf("counter:%d\n",counter);
pthread_t thrd1,thrd2;
int ret;
ret = pthread_create(&thrd1,NULL,decrement_count,NULL);
if(ret){
perror("de1:");
return 1;
}
ret = pthread_create(&thrd2,NULL,increment_count,NULL);
if(ret){
perror("in1:");
return 1;
}
int count=0;
while(count!=20){
printf("counter:%d\n",counter);
sleep(1);
count++;
}
return 0;
}
void * decrement_count (void * argv){
pthread_mutex_lock(&count_lock);
while(counter==0)
pthread_cond_wait(&count_nonzero,&count_lock);
counter--;
pthread_mutex_unlock(&count_lock);
return &estatus;
}
void * increment_count(void * argv){
pthread_mutex_lock(&count_lock);
if(counter==0)
pthread_cond_signal(&count_nonzero);
counter++;
pthread_mutex_unlock(&count_lock);
return &estatus;
}
如果我们调试程序会发现程序是如下运行的.
开始时 counter 为0,
ret = pthread_create(&thrd1,NULL,decrement_count,NULL)处生成一个thrd1线程运行decrement_count(),此线程内函数运行流程为:
锁定 互斥锁 count_lock,如果counter为0,此线程被阻塞在条件变量count_nonzero上.同时释放互斥锁count_lock.
与此同时主程序还在运行,创建另一个线程thrd2运行 increment_count,此线程内的函数流程如下:
锁定 互斥锁 count_lock,如果counter为0,唤醒在条件变量count_nonzero上的线程即thrd1.但是由于有互斥锁count_lock,thrd1还是在等待.然后count++,释放互斥锁,.......thrd1由于互斥锁释放,重新判断counter是不是为0,如果为0再把线程阻塞在条件变量count_nonzero上,但这时counter已经为1了.所以线程继续运行.counter--释放互斥锁......
与此主程序间隔打印counter运行一段时间退出.
后记,在编译的时候加上 -lpthread