条件变量用来阻塞一个线程,直到其他的线程通知它条件已满足为止;
条件变量看似简单,与互斥锁同时使用实现生产者消费者模型;
生产者消费者模型(高速缓存队列);
1)初始化条件变量
int pthread_cond_init(pthread_cond_t* cond,pthread_condattr_t* cond_attr) ;
2)阻塞等待
int pthread_cond_wait(pthread_cond_t* cond,pthread_mutex_t* mutex) ;
3)超时等待
int pthread_cond_timedwait(pthread_cond_t* cond,pthread_mutex* mutex,const timespec* abstime) ;
4)唤醒一个等待该条件的线程
int pthread_cond_signal(pthread_cond_t* cond) ;
5)唤醒全部等待该条件的所有线程
int pthread_cond_broadcast(pthread_cond_tcond) ;
6)销毁条件变量
int pthread_cond_destroy(pthread_cond_t cond) ;
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <queue>
#include <pthread.h>
using namespace std ;
#define MAX_QUEUE 5
int data = 0 ;
class BlockQueue{
private:
queue<int> _queue ;
int _capacity ;
pthread_mutex_t _mutex ;
pthread_cond_t _cond_con ;
pthread_cond_t _cond_pro ;
public:
BlockQueue(int cap = MAX_QUEUE)
:_capacity(cap){
pthread_mutex_init(&_mutex,NULL) ;
pthread_cond_init(&_cond_con,NULL) ;
pthread_cond_init(&_cond_pro,NULL) ;
}
~BlockQueue(){
pthread_cond_destroy(&_cond_pro) ;
pthread_cond_destroy(&_cond_con) ;
pthread_mutex_destroy(&_mutex) ;
}
bool Push(int data){
pthread_mutex_lock(&_mutex) ;
while(_queue.size() == _capacity){
pthread_cond_wait(&_cond_pro,&_mutex) ;
}
_queue.push(data) ;
pthread_mutex_unlock(&_mutex) ;
pthread_cond_signal(&_cond_con) ;
return true ;
}
bool Pop(int* data){
pthread_mutex_lock(&_mutex) ;
while(_queue.empty()){
pthread_cond_wait(&_cond_con,&_mutex) ;
}
*data = _queue.front() ;
_queue.pop() ;
pthread_mutex_unlock(&_mutex) ;
pthread_cond_signal(&_cond_pro) ;
return true ;
}
} ;
void* thr_con(void* arg){
BlockQueue* q = (BlockQueue*)arg ;
while(1){
int data ;
q->Pop(&data) ;
cout<<"consume --> "<<data<<endl ;
usleep(100) ;
}
return NULL ;
}
void* thr_pro(void* arg){
BlockQueue* q = (BlockQueue*)arg ;
while(1){
q->Push(data) ;
usleep(100) ;
cout<<"product -->"<<data++<<endl ;
}
return NULL ;
}
int main(){
int ret , i ;
pthread_t ctid[4] , ptid[4] ;
BlockQueue queue ;
for(i = 0 ; i<4 ; ++i){
ret = pthread_create(&ctid[i],NULL,thr_con,(void*)&queue) ;
if(ret != 0){
perror("create failure") ;
return -1 ;
}
}
for(i = 0 ; i<4 ; ++i){
ret = pthread_create(&ptid[i],NULL,thr_pro,(void*)&queue) ;
if(ret != 0){
perror("create failure") ;
return -1 ;
}
}
for(i = 0 ; i<4 ; ++i){
pthread_join(ctid[i],NULL) ;
pthread_join(ptid[i],NULL) ;
}
return 0 ;
}