一个C++的BlockingQueue实现
2011-02-18 00:00
369 查看
原文在
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
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) { boost::mutex::scoped_lock lock(the_mutex); the_queue.push(data); lock.unlock(); 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++实现两有序链表合并成一个新链表
- 004使用一个栈对另一个栈完成排序(C++实现)
- 一个c++实现的链表,如下:
- 自己动手实现一个C++智能指针
- C++实现一个航空订票程序 来自明桑Android
- C++简单实现一个内存池的分配
- 【C++】模拟实现一个复数类,要求实现 加,减,乘,除等基本运算符的重载
- 一个简单的二叉搜索树(C++实现)
- c++ template 实现一个简单的"栈"
- C++异常机制的实现方式和开销分析 (大图,编译器会为每个函数增加EHDL结构,组成一个单向链表,非常著名的“内存访问违例”出错对话框就是该机制的一种体现)
- C++ 模板应用 实现一个Queue 队列
- 学习实践:使用模式,原则实现一个C++数据库访问类
- 统计一个Byte中1的个数,算法尽可能高性能——C++实现
- C++实现垃圾回收,不小心把老文章删除了,重新补发一个
- 采用C++的ACE库实现的一个通用的C/S架构通信程序(最终版)
- binder 一个简单的c++服务的实现,与callback实现
- C++ 根据复合实现出 有一个 或 根据某物实现出
- 《剑指Offer》附加题_用两个队列实现一个栈_C++版
- C++实现将一个字符串中的字符替换成另一个字符串的方法
- 用C++实现void reverse(char* str)函数,即反转一个null结尾的字符串.