使用C++ 11 实现阻塞队列
2015-08-17 20:53
686 查看
阻塞队列介绍
阻塞队列主要用于线程和线程之间的通信。当队列为空时,从队列中获取元素的线程将会被挂起;当队列是满时,往队列里添加元素的线程将会挂起。本文使用C++ 11中的多线程库,实现了一个带有最大容量的阻塞队列。代码使用Visual C++ 2015编写。
阻塞队列的实现代码
BlockQueue.hpp#pragma once #include <condition_variable> #include <mutex> #include <deque> template<class T> class BlockQueue { public: typedef std::unique_lock<std::mutex> TLock; //maxCapacity为-1,代表队列无最大限制 explicit BlockQueue(const int maxCapacity = -1):m_maxCapacity(maxCapacity) { } size_t size() { TLock lock(m_mutex); return m_list.size(); } void push_back(const T &item) { TLock lock(m_mutex); if (true == hasCapacity()) { while (m_list.size() >= m_maxCapacity) { m_notFull.wait(lock); } } m_list.push_back(item); m_notEmpty.notify_all(); } T pop() { TLock lock(m_mutex); while (m_list.empty()) { m_notEmpty.wait(lock); } T temp = *m_list.begin(); m_list.pop_front(); m_notFull.notify_all(); lock.unlock(); return temp; } bool empty() { TLock lock(m_mutex); return m_list.empty(); } bool full() { if (false == hasCapacity) { return false; } TLock lock(m_mutex); return m_list.size() >= m_maxCapacity; } private: bool hasCapacity() const { return m_maxCapacity > 0; } typedef std::deque<T> TList; TList m_list; const int m_maxCapacity; std::mutex m_mutex; std::condition_variable m_notEmpty; std::condition_variable m_notFull; };
测试代码
#include <iostream> #include <thread> #include <stdio.h> #include "BlockQueue.hpp" using namespace std; typedef BlockQueue<int> TQueue; void produce(TQueue &queue) { const int num = 9; for (int i = 0; i < num; ++i) { queue.push_back(i); } } void consume(TQueue &queue) { while (false==queue.empty()) { int tmp = queue.pop(); printf("%d\n", tmp); std::this_thread::sleep_for(chrono::seconds(1)); } } int main() { TQueue queue(2); std::thread t1(produce, std::ref(queue)); std::thread t2(consume, std::ref(queue)); std::thread t3(consume, std::ref(queue)); t3.join(); t2.join(); t1.join(); return 0; }
相关文章推荐
- HDOJ1085母函数的应用
- Effective C++ 条款2 尽量以const,enum,inline替换#define
- 黑马程序员-[OC语言] 第六篇:foundation框架之 NSString 基本用法
- 黑马程序员-[OC语言] 第四篇:ARC机制、类别 概述
- (C++ 11) 泛型算法(一)
- 黑马程序员-[OC语言] 第三篇:MRC手动内存管理总结
- C++ Read a whole File using ifstream
- 黑马程序员-[OC语言] 第二篇:继承、多态概述
- 线性表(顺序存储)C语言实现
- c/c++编译时,指定程序运行时查找的动态链接库路径
- 黑马程序员-[OC语言] 第一篇:类、对象的基本概述
- C++11新特性之自动类型判断以及匿名函数
- C++11新特性之std::bind与std::function
- C语言宏定义小结
- c++ assert
- Effective C++ 条款1 视C++为一个语言联邦
- 关于OJ G++ 、C++提交
- C语言实现 前序、中序、后序遍历二叉树
- 队列(C语言版)
- 黑马程序员-[C语言] 第四篇:文件操作总结