C++ 阻塞队列
来源:互联网 发布:专业网络k歌声卡 编辑:程序博客网 时间:2024/05/18 00:09
阻塞队列也是多线程项目中常用的东西,特别适用于生产者/消费者的场景,我这分别用windows api 和 c++11 实现
windows版:
#include <queue>#include <windows.h>using namespace std;template<class T>class BlockingQueue{public: BlockingQueue(int size):maxSize(size){isAlive = true; _lock = CreateMutex(NULL,false,NULL); _rsem = CreateSemaphore(NULL,0,size,NULL); _wsem = CreateSemaphore(NULL,size,size,NULL); }~BlockingQueue() { CloseHandle(_lock); CloseHandle(_rsem); CloseHandle(_wsem); }void Close() {isAlive = false;ReleaseMutex(_lock);ReleaseSemaphore(_rsem, 1, NULL); } void push(const T& data){if (isAlive) {WaitForSingleObject(_wsem, INFINITE);WaitForSingleObject(_lock, INFINITE);_array.push(data);ReleaseMutex(_lock);ReleaseSemaphore(_rsem, 1, NULL);} } T pop(){ WaitForSingleObject(_rsem,INFINITE); WaitForSingleObject(_lock,INFINITE);if(!isAlive){throw exception();} T _temp = _array.front();_array.pop();ReleaseMutex(_lock); ReleaseSemaphore(_wsem,1,NULL); return _temp; }int GetLength() {return _array.size(); }private: queue<T> _array; HANDLE _lock; HANDLE _rsem, _wsem; int maxSize;bool isAlive;};
c++11
#pragma once#include <mutex>#include <condition_variable>#include <deque>#include <iostream>using namespace std;template <typename T>class BlockingQueue{private:BlockingQueue(const BlockingQueue& rhs);BlockingQueue& operator =(const BlockingQueue& rhs);mutable mutex _mutex;condition_variable _condvar;deque<T> _queue;bool isShutDown = false;public:BlockingQueue(): _mutex() , _condvar() , _queue(){}~BlockingQueue(){cout << "blocking queue release" << endl;}void ShutDown(){isShutDown = true;_condvar.notify_all();_queue.clear();}bool IsShutDown(){return isShutDown;}void Put(const T task){lock_guard<mutex> lock(_mutex);if (!isShutDown){{_queue.push_back(task);}_condvar.notify_all();}}T Take(){unique_lock<mutex> lock(_mutex);if(_queue.size()<=0)_condvar.wait(lock);if (isShutDown||_queue.empty()){throw exception();}T front(_queue.front());_queue.pop_front();return front;}size_t Size() const{lock_guard<mutex> lock(_mutex);return _queue.size();}};
阅读全文
0 0
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- 阻塞队列
- SpringAOP之注入AspectJ切面
- more than one `-Acdtrux' or `--test-label' option
- 经典动态规划之最长上升子序列
- 使用maven和springMVC项目的结构
- Runtime linking on Mac
- C++ 阻塞队列
- 网络七层模型
- 我的博客
- HDU-1074-状态压缩DP
- The last packet sent successfully to the server was 0 milliseconds ago问题的解决
- 斯特林公式--求阶乘近似值
- 手机通讯模块开发协议文档索引
- SQL优化
- openCV之图像混合