现在的位置: 首页 > 综合 > 正文

条件变量:BlockingQueue+CountDownLatch 条件变量:BlockingQueue+CountDownLatch

2017年09月29日 ⁄ 综合 ⁄ 共 7807字 ⁄ 字号 评论关闭
 

条件变量:BlockingQueue+CountDownLatch

分类: Linux多线程编程 241人阅读 评论(0) 收藏 举报

     条件变量pthread_cond_t又名管程,条件变量的正确使用方式:

1 必须与pthread_mutex_t一起使用,条件的读写受互斥量保护

2 必须在pthread_mutex_lock后才能调用pthread_cond_wait

3 采用while抱住pthread_cond_wait,这样防止虚假唤醒(线程甚至在没有其它向条件变量发送信号的情况下就有可能会被唤醒)

    阻塞队列:

    BlockingQueue:阻塞队列与普通队列的区别在于,当队列是空的时,从队列中获取元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞。试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。同样,试图往已满的阻塞队列中添加新元素的线程同样也会被阻塞,直到其他的线程使队列重新变得空闲起来,如从队列中移除一个或者多个元素,或者完全清空队列。

    CountDownLatch:CountDownLatch类是一个同步倒数计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0 时,await()方法会阻塞后面程序执行,直到计数器为0

  1. #include<iostream>  
  2. #include<assert.h>  
  3. #include<pthread.h>  
  4. #include<unistd.h>  
  5. #include<boost/noncopyable.hpp>  
  6. #include<deque>  
  7. using namespace std;  
  8. using namespace boost;  
  9. class Mutex:public noncopyable{//互斥量的封装  
  10.     public:  
  11.         Mutex(){  
  12.             pthread_mutex_init(&mutex,NULL);  
  13.         }  
  14.         void lock(){  
  15.             pthread_mutex_lock(&mutex);  
  16.         }  
  17.         void unlock(){  
  18.             pthread_mutex_unlock(&mutex);  
  19.         }  
  20.         ~Mutex(){  
  21.             pthread_mutex_destroy(&mutex);  
  22.         }  
  23.         pthread_mutex_t* getMutex(){  
  24.             return &mutex;  
  25.         }  
  26.     private:  
  27.         mutable pthread_mutex_t mutex;  
  28. };  
  29. class MutexLockGuard:noncopyable{//RAII管理互斥量  
  30.     public:  
  31.         explicit MutexLockGuard(Mutex& mutex):mutex_(mutex){  
  32.             mutex_.lock();  
  33.         }  
  34.         ~MutexLockGuard(){  
  35.             mutex_.unlock();  
  36.         }  
  37.     private:  
  38.         Mutex& mutex_;//注意是引用,Mutex继承了noncopyable后不能拷贝构造  
  39. };  
  40. class Condition:public noncopyable{//条件变量的封装  
  41.     public:  
  42.         explicit Condition(Mutex& mutex):mutex_(mutex){  
  43.             pthread_cond_init(&cond,NULL);  
  44.         }  
  45.         ~Condition(){  
  46.             pthread_cond_destroy(&cond);  
  47.         }  
  48.         void wait(){  
  49.             pthread_cond_wait(&cond,mutex_.getMutex());  
  50.         }  
  51.         void notify(){  
  52.             pthread_cond_signal(&cond);  
  53.         }  
  54.         void notifyALL(){  
  55.             pthread_cond_broadcast(&cond);  
  56.         }  
  57.     private:  
  58.         Mutex& mutex_;//注意是引用  
  59.         pthread_cond_t cond;  
  60. };  
  61. template<typename T>//队列任务T  
  62. class BlockingQueue:noncopyable{//无限容量的阻塞队列  
  63.     public:  
  64.         BlockingQueue():mutex(),notEmpty(mutex),Q(){}  
  65.         void put(const T& x){//向队列添加任务T  
  66.             MutexLockGuard guard(mutex);//栈对象  
  67.             Q.push_back(x);  
  68.             notEmpty.notifyALL();//唤醒等待条件上的线程  
  69.             cout<<"put()"<<endl;  
  70.         }  
  71.         T take(){//获取一个队列任务  
  72.             MutexLockGuard guard(mutex);  
  73.             while(Q.empty()){//循环抱住以防止假唤醒  
  74.                 cout<<"Q.empty()"<<endl;  
  75.                 notEmpty.wait();//原子的解锁mutex并进入等待,不会与put死锁  
  76.             }  
  77.             assert(!Q.empty());  
  78.             T front(Q.front());//这里假设T允许拷贝构造  
  79.             Q.pop_front();  
  80.             cout<<"take()"<<endl;  
  81.             return front;  
  82.         }  
  83.         size_t size() const{//返回队列大小  
  84.             MutexLockGuard guard(mutex);  
  85.             return Q.size();  
  86.         }  
  87.     private:  
  88.         mutable Mutex mutex;//互斥锁保护队列  
  89.         Condition notEmpty;//条件变量  
  90.         deque<T> Q;  
  91. };  
  92. class test{//任务T类型  
  93.     public:  
  94.         void show(){  
  95.             cout<<"show()"<<endl;  
  96.         }  
  97. };  
  98. BlockingQueue<test*> bq;  
  99. void* worker1(void* arg){//线程1,添加一个T到任务队列  
  100.     sleep(2);  
  101.     test* temp=(test*)arg;  
  102.     bq.put(temp);  
  103. }  
  104. void* worker2(void* arg){//线程2,从任务队列获取一个T  
  105.     //sleep(1);  
  106.     test* temp=bq.take();  
  107.     temp->show();  
  108. }  
  109. int main(){  
  110.     pthread_t pid1,pid2;  
  111.     test* temp=new test;  
  112.     pthread_create(&pid1,NULL,worker1,&temp);  
  113.     pthread_create(&pid2,NULL,worker2,NULL);  
  114.     pthread_join(pid1,NULL);  
  115.     pthread_join(pid2,NULL);  
  116.     delete temp;  
  117.     return 0;  
  118. }  

输出:

Q.empty()
put()
take()
show()

采用CoutDownLatch作为同步线程间工具:

  1. #include<iostream>  
  2. #include<assert.h>  
  3. #include<pthread.h>  
  4. #include<unistd.h>  
  5. #include<boost/noncopyable.hpp>  
  6. #include<deque>  
  7. using namespace std;  
  8. using namespace boost;  
  9. class Mutex:public noncopyable{//互斥量的封装  
  10.     public:  
  11.         Mutex(){  
  12.             pthread_mutex_init(&mutex,NULL);  
  13.         }  
  14.         void lock(){  
  15.             pthread_mutex_lock(&mutex);  
  16.         }  
  17.         void unlock(){  
  18.             pthread_mutex_unlock(&mutex);  
  19.         }  
  20.         ~Mutex(){  
  21.             pthread_mutex_destroy(&mutex);  
  22.         }  
  23.         pthread_mutex_t* getMutex(){  
  24.             return &mutex;  
  25.         }  
  26.     private:  
  27.         mutable pthread_mutex_t mutex;  
  28. };  
  29. class MutexLockGuard:noncopyable{//RAII管理互斥量  
  30.     public:  
  31.         explicit MutexLockGuard(Mutex& mutex):mutex_(mutex){  
  32.             mutex_.lock();  
  33.         }  
  34.         ~MutexLockGuard(){  
  35.             mutex_.unlock();  
  36.         }  
  37.     private:  
  38.         Mutex& mutex_;//注意是引用,Mutex继承了noncopyable后不能拷贝构造  
  39. };  
  40. class Condition:public noncopyable{//条件变量的封装  
  41.     public:  
  42.         explicit Condition(Mutex& mutex):mutex_(mutex){  
  43.             pthread_cond_init(&cond,NULL);  
  44.         }  
  45.         ~Condition(){  
  46.             pthread_cond_destroy(&cond);  
  47.         }  
  48.         void wait(){  
  49.             pthread_cond_wait(&cond,mutex_.getMutex());  
  50.         }  
  51.         void notify(){  
  52.             pthread_cond_signal(&cond);  
  53.         }  
  54.         void notifyALL(){  
  55.             pthread_cond_broadcast(&cond);  
  56.         }  
  57.     private:  
  58.         Mutex& mutex_;//注意是引用  
  59.         pthread_cond_t cond;  
  60. };  
  61. template<typename T>//队列任务T  
  62. class BlockingQueue:noncopyable{//无限容量的阻塞队列  
  63.     public:  
  64.         BlockingQueue():mutex(),notEmpty(mutex),Q(){}  
  65.         void put(const T& x){//向队列添加任务T  
  66.             MutexLockGuard guard(mutex);//栈对象  
  67.             Q.push_back(x);  
  68.             notEmpty.notifyALL();//唤醒等待条件上的线程  
  69.             cout<<"put()"<<endl;  
  70.         }  
  71.         T take(){//获取一个队列任务  
  72.             MutexLockGuard guard(mutex);  
  73.             while(Q.empty()){//循环抱住以防止假唤醒  
  74.                 cout<<"Q.empty()"<<endl;  
  75.                 notEmpty.wait();//原子的解锁mutex并进入等待,不会与put死锁  
  76.             }  
  77.             assert(!Q.empty());  
  78.             T front(Q.front());//这里假设T允许拷贝构造  
  79.             Q.pop_front();  
  80.             cout<<"take()"<<endl;  
  81.             return front;  
  82.         }  
  83.         size_t size() const{//返回队列大小  
  84.             MutexLockGuard guard(mutex);  
  85.             return Q.size();  
  86.         }  
  87.     private:  
  88.         mutable Mutex mutex;//互斥锁保护队列  
  89.         Condition notEmpty;//条件变量  
  90.         deque<T> Q;  
  91. };  
  92. class test{//任务T类型  
  93.     public:  
  94.         void show(){  
  95.             cout<<"show()"<<endl;  
  96.         }  
  97. };  
  98. class CountDownLatch:noncopyable{//  
  99.     public:  
  100.         explicit CountDownLatch(int count):mutex(),condition(mutex),cnt(count){}//mutex要先于condition构造  
  101.         void wait(){//阻塞等待计数为0  
  102.             MutexLockGuard guard(mutex);  
  103.             while(cnt>0){  
  104.                 condition.wait();  
  105.             }  
  106.         }  
  107.         void countDown(){//将计数减1  
  108.             MutexLockGuard guard(mutex);  
  109.             --cnt;  
  110.             if(cnt==0){  
  111.                 condition.notifyALL();//  
  112.             }  
  113.         }  
  114.         int getCount() const{  
  115.             MutexLockGuard guard(mutex);  
  116.             return cnt;  
  117.         }  
  118.     private:  
  119.         mutable Mutex mutex;  
  120.         Condition condition;  
  121.         int cnt;  
  122. };  
  123. BlockingQueue<test*> bq;  
  124. CountDownLatch latch(1);//计数为1  
  125. void* worker1(void* arg){//线程1,添加一个T到任务队列  
  126.     //sleep(2);  
  127.     latch.countDown();//线程1将计数减一  
  128.     test* temp=(test*)arg;  
  129.     bq.put(temp);  
  130. }  
  131. void* worker2(void* arg){//线程2,从任务队列获取一个T  
  132.     //sleep(1);  
  133.     latch.wait();//线程2等待计数为0  
  134.     test* temp=bq.take();  
  135.     temp->show();  
  136. }  
  137. int main(){  
  138.     pthread_t pid1,pid2;  
  139.     test* temp=new test;  
  140.     pthread_create(&pid1,NULL,worker1,&temp);  
  141.     pthread_create(&pid2,NULL,worker2,NULL);  
  142.     pthread_join(pid1,NULL);  
  143.     pthread_join(pid2,NULL);  
  144.     delete temp;  
  145.     return 0;  
  146. }  

程序输出:

put()
take()
show()

抱歉!评论已关闭.