线程间同步,条件变量,互斥锁的使用

http://blog.chinaunix.net/uid-24922718-id-3311199.html


  1. #include <iostream>
  2. #include <pthread.h>
  3. using namespace std;

  4. pthread_cond_t qready = PTHREAD_COND_INITIALIZER;    //初始构造条件变量
  5. pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;    //初始构造锁
  6. pthread_t tid1,tid2,tid3;

  7. int x = 10;
  8. int y = 20;


  9. void *thrd_1(void *arg)
  10. {
  11.     pthread_mutex_lock(&qlock);
  12.     while(x<y)
  13.     {
  14.         pthread_cond_wait(&qready,&qlock);
  15.     }
  16.     pthread_mutex_unlock(&qlock);
  17.     cout<<"1"<<endl;
  18.     sleep(5);
  19. }

  20. void *thrd_2(void *arg)
  21. {
  22.     pthread_mutex_lock(&qlock);
  23.     x = 20;
  24.     y = 10;
  25.     cout<<"has change x and y"<<endl;

  26.     pthread_mutex_unlock(&qlock);
  27.     if(> y)
  28.     {
  29.         pthread_cond_signal(&qready);
  30.     }
  31.     cout<<"2"<<endl;
  32. }

  33. void *thrd_3(void *arg)
  34. {
  35.     pthread_join(tid1,NULL);
  36.     cout<<"3"<<endl;
  37. }

  38. int main(int argc,char **argv)
  39. {
  40.     int err;
  41.     err = pthread_create(&tid1,NULL,thrd_1,NULL);
  42.     if(err != 0)
  43.     {
  44.         cout<<"pthread 1 create error"<<endl;
  45.     }
  46.     err = pthread_create(&tid2,NULL,thrd_2,NULL);
  47.     if(err != 0)
  48.     {
  49.         cout<<"pthread 2 create error"<<endl;
  50.     }
  51.     err = pthread_create(&tid3,NULL,thrd_3,NULL);
  52.     if(err != 0)
  53.     {
  54.         cout<<"pthread 3 create error"<<endl;
  55.     }
  56.     while(1)
  57.     {
  58.         sleep(1);
  59.     }
  60.     return 0;
  61.     
  62. }
可以看到,创建了3个线程后,执行顺序2,1,3,即打印出的数字是213。为什么是这个顺序呢?我们接下去看,当创建tid1线程的时候,进入线程函数,并且加上了锁,然后进入pthread_cond_wait函数,这个函数的功能是等待qready这个条件变量成功,这个条件是什么呢?我们稍后在看,现在我们只要知道,这个函数在qready条件没满足的时候会卡在这里,并且,会把传入的互斥锁解锁,为什么要解锁的,拟可以想想,如果不解锁的话,那外部就没有可以对x,y的修改权,应为其他两个线程想要修改这两个值的话都需要对qclock进行枷锁。
好了线程1就这样,那之后就会运行线程2,我们看线程2的线程函数,该函数一开始也加了锁,但当线程1的pthread_cond_wait解锁之后,他就可以继续运行了,并且,在之后,它对x,y进行了修改,改好之后进行了解锁,并且调用了pthread_cond_signal通知线程1,现在可以知道了吧。这个满足的条件就是要x>y。
   现在这里有个问题,一定要在发送通知之前解锁吗?答案是肯定的,为什么,因为如果先发送通知信号给线程1的时候,pthread_cond_wait可能在线程2的解锁之前就返回,而当它返回的时候,会再次将这个所进行锁定,而这个所还没有在线程2中解锁,应次会使其在次卡住。虽然这个卡住在线程2运行到解锁处会消除,但这并不符合我们有时的需求,所以最好还是在解锁之后在发送信号。
    所以可以看出为什么线程2总是在线程1之前执行完毕,线程3就更不用说了,pthread_join你们懂的!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值