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

版权声明:本文为博主原创文章,未经博主允许不得转载。博客主页:http://blog.csdn.net/u013390476 https://blog.csdn.net/u013390476/article/details/52067321

前言

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

猜你喜欢

转载自blog.csdn.net/u013390476/article/details/52067321