生产者-消费者,使用C++11的版本
2016-07-29 17:45
176 查看
前言
multi-threading以及lambda是C++11的重要升级,下面的经典的生产者-消费者的代码,既使用了C++11的multi-threading相关的库, 又使用了lambda。代码中有注释,应该比较详细。Talk is cheap show me the code
#include <iostream> #include <queue> #include <thread> #include <mutex> #include <condition_variable> using namespace std; mutex mtx; condition_variable produce, consume; // 条件变量是一种同步机制,要和mutex以及lock一起使用 queue<int> q; // shared value by producers and consumers, which is the critical section int maxSize = 20; void consumer() { while (true) { this_thread::sleep_for(chrono::milliseconds(1000)); unique_lock<mutex> lck(mtx); // RAII,程序运行到此block的外面(进入下一个while循环之前),资源(内存)自动释放 consume.wait(lck, [] {return q.size() != 0; }); // wait(block) consumer until q.size() != 0 is true cout << "consumer " << this_thread::get_id() << ": "; q.pop(); cout << q.size() << '\n'; produce.notify_all(); // nodity(wake up) producer when q.size() != maxSize is true } } void producer(int id) { while (true) { this_thread::sleep_for(chrono::milliseconds(900)); // producer is a little faster than consumer unique_lock<mutex> lck(mtx); produce.wait(lck, [] {return q.size() != maxSize; }); // wait(block) producer until q.size() != maxSize is true cout << "-> producer " << this_thread::get_id() << ": "; q.push(id); cout << q.size() << '\n'; consume.notify_all(); // notify(wake up) consumer when q.size() != 0 is true } } int main() { thread consumers[2], producers[2]; // spawn 2 consumers and 2 producers: for (int i = 0; i < 2; ++i) { consumers[i] = thread(consumer); producers[i] = thread(producer, i + 1); } // join them back: (in this program, never join...) for (int i = 0; i < 2; ++i) { producers[i].join(); consumers[i].join(); } system("pause"); return 0; }
扩展阅读
生产者-消费者模型扩展我的GitHub里的一个项目:线程池(使用C++11)
为什么条件变量和互斥锁要在一起使用。这篇博客使用类Unix操作系统的POSIX multithreading,来讲解条件变量(condition variable) 为什么,以及怎么和互斥锁(mutex and lock)一起配套使用。
Last update: 2017/7/27
相关文章推荐
- C语言 程序 素数圈圈
- 二叉树以及 二叉树的C++实现
- C 内存管理详解
- Emacs杂谈(一)Emacs环境 c++ 快捷键
- Emacs杂谈(一)Emacs环境 c++ 快捷键
- C++ stl队列Queue用法介绍:删除,插入等操作代码举例
- C++ 的枚举和宏
- c++ stl栈容器stack的pop(),push()等用法介绍及头文件
- 快速幂取模_C++
- C++复习之冒泡排序&插入排序&希尔排序
- C++中public,protected,private的区别
- C++ vector容器类型
- 模板的概念
- 趣味100道C语言编程题num ten
- 七大查找算法(附C语言代码实现)
- 第三章 C++之VC++6.0使用与快捷键
- c语言描述的静态查找表
- c++、java CRC16算法
- 字符串翻转和旋转问题和例题
- 数组中只出现一次的数字 C++