Linux C++ 使用condition实现阻塞队列的方法
程序员文章站
2022-07-11 08:18:37
实例如下:
/*
* blockingqueue.h
*
* created on: 2014年6月10日
* author:
*/...
实例如下:
/* * blockingqueue.h * * created on: 2014年6月10日 * author: */ #ifndef blockingqueue_h_ #define blockingqueue_h_ #include <iostream> #include <pthread.h> using namespace std; //template <typename t > class blockingqueue { public: blockingqueue(); blockingqueue(int capacity); ~blockingqueue(); bool push(int item); int poll(); private: int capacity; int* queue; int head,tail; pthread_mutex_t mutex; pthread_cond_t notfull,notempty; }; #endif /* blockingqueue_h_ */
/* * blockingqueue.cpp * * created on: 2014年6月10日 * author: */ #include "../include/blockingqueue.h" blockingqueue::blockingqueue() { this->capacity = 10; queue = new int[capacity]; head = 0,tail = 0; pthread_mutex_init(&mutex,null); pthread_cond_init(¬full,null); pthread_cond_init(¬empty,null); } blockingqueue::blockingqueue(int capacity) { this->capacity = capacity; queue = new int[capacity]; cout << "capacity " << sizeof(queue) << endl; head = 0,tail = 0; pthread_mutex_init(&mutex,null); pthread_cond_init(¬full,null); pthread_cond_init(¬empty,null); } blockingqueue::~blockingqueue() { this->capacity = 0; head = 0,tail = 0; delete queue; pthread_mutex_destroy(&mutex); pthread_cond_destroy(¬full); pthread_cond_destroy(¬empty); } bool blockingqueue::push(int item) { pthread_mutex_lock(&mutex); cout << "you want push " << item << endl; while((head + 1) % capacity == tail)//is full { cout << "is full,wait..." << endl; // push wait pthread_cond_wait(¬full,&mutex); cout << "not full,unlock" << endl; } { queue[head] = item; head = (head + 1) % capacity; cout << "push " << item << endl; //wake up poll thread pthread_cond_signal(¬empty); pthread_mutex_unlock(&mutex); return true; } } int blockingqueue::poll() { pthread_mutex_lock(&mutex); int ret = 0; while(head == tail) // is empty { cout << "is empty,wait..." << endl; //poll wait pthread_cond_wait(¬empty,&mutex); cout << "not empty,unlock..." << endl; } { ret = queue[tail]; tail = (tail + 1) % capacity; cout << "take " << ret << endl; //wake up push thread pthread_cond_signal(¬full); pthread_mutex_unlock(&mutex); return ret; } }
#include <iostream> #include "include/blockingqueue.h" using namespace std; blockingqueue queue(3); void* put(void *) { queue.push(1); queue.push(2); queue.push(3); queue.push(4); queue.push(5); return null; } void* take(void *) { queue.poll(); queue.poll(); queue.poll(); return null; } int main() { pthread_t put1,take1; pthread_create(&put1,null,put,0); pthread_create(&take1,null,take,0); void * retval; pthread_join(put1,&retval); pthread_join(take1,&retval); return 0; }
以上就是小编为大家带来的linux c++ 使用condition实现阻塞队列的方法全部内容了,希望大家多多支持~
上一篇: Linux多线程锁属性设置方法
下一篇: Linux恢复删除文件的lsof命令详解