C++线程安全队列
2016-05-31 13:25
381 查看
template<typename Data> class concurrent_queue { private: std::queue<Data> the_queue; mutable boost::mutex the_mutex; boost::condition_variable the_condition_variable; public: void push(Data const& data) { #if 0 boost::mutex::scoped_lock lock(the_mutex); the_queue.push(data); lock.unlock(); #else //利用作用域自动释放锁,防止异常崩溃场景 { boost::mutex::scoped_lock lock(the_mutex); the_queue.push(data); } #endif the_condition_variable.notify_one(); } bool empty() const { boost::mutex::scoped_lock lock(the_mutex); return the_queue.empty(); } //获取队列头部的值,并移除队列头部 bool try_pop(Data& popped_value) { boost::mutex::scoped_lock lock(the_mutex); if(the_queue.empty()) { return false; } popped_value=the_queue.front(); the_queue.pop(); return true; } //等待队列有值,再弹出队列的头部 void wait_and_pop(Data& popped_value) { boost::mutex::scoped_lock lock(the_mutex); while(the_queue.empty()) { the_condition_variable.wait(lock); } popped_value=the_queue.front(); the_queue.pop(); } };
相关文章推荐
- C++队列模板使用std::queue
- C++ Unicode与UTF_8 编码转换
- C语言 break跳出循环
- OC语言6—继承
- 让自己的C++程序(非服务程序)运行为一个windows service
- OC语言5—封装
- android studio 2.2 C++ 支持(CMAKE方法)
- OC语言4-内存管理
- C++移位运算符
- 2016从零开始纯C语言、C++语言一步一步完成RPG大型游戏开发
- C/C++struct与C++struct/class关键字详解
- 二路归并排序算法实现-完整C语言程序
- 【LeetCode】215. Kth Largest Element in an Array,基于Java和C++的解法
- [Error] ISO C++ forbids comparison between pointer and integer [-fpermiss
- c++ 每周一些题(5)
- 河南第五届省赛 B 最强DE 战斗力 -- (大数乘法 c++ OR java)
- 二叉排序树(BST)的思路及C语言实现
- C++延时函数
- 感知机c/c++代码实现
- c++中this指针的用法详解