Chinaunix首页 | 论坛 | 博客
  • 博客访问: 645957
  • 博文数量: 404
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 1237
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-03 10:45
文章分类

全部博文(404)

文章存档

2017年(1)

2016年(27)

2015年(39)

2014年(55)

2013年(66)

2012年(216)

分类:

2012-08-15 10:11:17

    线程间的同步技术,主要以互斥锁和条件变量为主,条件变量和互斥所的配合使用可以很好的处理对于条件等待的线程间的同步问题。举个例子:当有两个变量x,y需要在多线程间同步并且学要根据他们之间的大小比较来启动不同的线程执行顺序,这便用到了条件变量这一技术。看代码

点击(此处)折叠或打开

  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(x > 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你们懂的!!!

阅读(231) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~