一个C++异步队列的测试程序
来源:互联网 发布:物流打印软件 编辑:程序博客网 时间:2024/05/20 03:42
#include <boost/thread.hpp>#include <unistd.h>#include <stdio.h>#include <queue>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(); } size_t size() const { boost::mutex::scoped_lock lock(the_mutex); return the_queue.size(); }};concurrent_queue<int> queue;class threadObj{public: void operator()() { run(); }protected: virtual void run() = 0;};class threadProducer : public threadObj{private: void run() { for(int i = 0; i < 100; i++) { usleep(20*1000); queue.push(i); printf("producer: %d\n", i); } }};class threadConsumer : public threadObj{private: void run() { for(int i = 0; i < 100; i++) { int j = 0; queue.wait_and_pop(j); printf("\t\tconsumer: %d\n", j); usleep(10*1000); } }};int main(int argc, char *argv[]){ printf("MAIN START\n"); boost::thread *consumer = new boost::thread(threadConsumer()); boost::thread *producer = new boost::thread(threadProducer()); producer->join(); consumer->join(); printf("MAIN END\n"); return 0;}
阅读全文
0 0
- 一个C++异步队列的测试程序
- 一个简单的测试程序健壮性的c程序
- 优先队列测试程序
- 数据结构循环队列的实现c程序
- 纯c封装的一个队列
- C语言一个队列的实现
- C语言一个队列的实现
- 一个通用纯C队列的实现
- C语言一个队列的实现
- C语言一个队列的实现
- Linux平台下从零开始写一个C语言访问MySQL的测试程序
- c-ares 一个C语言的异步DNS解析库
- 一个无常的C程序
- 一个搞笑的C程序
- 一个有趣的C程序
- 一个搞笑的C程序
- 一个简单的C程序
- 一个简单的C程序
- 09:明明的随机数
- SpringMVC项目的搭建过程
- 浅拷贝和深拷贝
- Python 基础语法
- OC : NSFastEnumeration (快速枚举)
- 一个C++异步队列的测试程序
- Python 设计模式
- 如何搭建直播平台?低延时连麦+人工智能让互动升级
- 【DIY】打造一个六足蜘蛛机器人
- PHP通过PHP QR Code生成二维码
- Spring MVC中快速集成swagger2
- Oracle介绍(一)
- ionic3三种跳转方法对应的页面间数据传递及Events
- 基于HtmlUnit获取页面表格信息