生产者-消费者,使用C++11的版本

来源:互联网 发布:中国程序员大神 编辑:程序博客网 时间:2024/06/05 03:19

前言

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;queue<int> q;     // shared value by producers and consumers, which is the critical sectionint 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 when q.size() == 0        cout << "consumer " << this_thread::get_id() << ": ";        q.pop();        cout << q.size() << '\n';        produce.notify_all();                               // nodity(wake up) producer when q.size() != maxSize    }}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 when q.size() == maxSize         cout << "-> producer " << this_thread::get_id() << ": ";        q.push(id);        cout << q.size() << '\n';        consume.notify_all();                                   // notify(wake up) consumer when q.size() != 0        }}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)

1 0
原创粉丝点击