c++生产者和消费者多线程实现

基于C++的生产者和消费者实现:

  1. std::condition_variable简单实用;
  2. 随机数简单使用;
  3. std::thread简单使用;

代码如下

#include <iostream>
#include <chrono>
#include <string>
#include <list>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <random>
using namespace std;
struct Good
{
    int id;
    string name;
    string prouct_date;
    int keeptime;
    string to_string()
    {
        return string("[")
        +string("id:")
        +std::to_string(id)
        +string(",")
        +string("name:")+name
        +string(",")
        +string("prouct_date:")+prouct_date
        +string(",")
        +string("keeptime:")+std::to_string(keeptime)
        +string("]");
    }
};
// 获取当时系统时间
const std::string GetCurrentSystemTime()
{
	time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
	struct tm* ptm = localtime(&t);
	char date[64] = { 0 };
	sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",
		(int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday,
		(int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
	return move(std::string(date));
}
std::list<Good> queue;
std::condition_variable condition;
class Producter
{
public:
    Producter()
    {

    }
    void prouct()
    {
        while(1)
        {
            Good good;
            good.id = id++;
            good.prouct_date = GetCurrentSystemTime();
            good.name = string("good");
            good.keeptime = 100000;
            std::unique_lock<std::mutex> lock(mutex);
            condition.wait(lock,[this](){
                // std::cout << "producter:queue.size = " << queue.size() << std::endl;
                return (queue.size() <= 100);
            });
            queue.push_back(good);
            std::cout <<  "生产者:" << good.to_string() << std::endl;
            condition.notify_one();
            default_random_engine e(time(NULL));
            this_thread::sleep_for(chrono::milliseconds(e()%1000));
        }

    }
private:
    int id = 0;
    std::mutex mutex;
    // std::condition_variable condition;
};
class Producer
{
public:
    Producer()
    {

    }
    void produce()
    {
        while(1)
        {
            std::unique_lock<std::mutex> lock(mutex);
            condition.wait(lock,[this](){
                // std::cout << "producer:queue.size = " << queue.size() << std::endl;
                return (queue.size() > 0);
            });
            Good good = queue.front();
            std::cout << "消费者:"<< good.to_string() << std::endl;
            queue.pop_front();
            condition.notify_one();
            default_random_engine e{random_device{}()};
            this_thread::sleep_for(chrono::milliseconds(e()%1000));
        }

    }
private:
    std::mutex mutex;
    
};

int main(int argc,char** argv)
{
    Producter *pdt = new Producter();
    Producer *pdc = new Producer();
    
    std::thread(&Producer::produce,pdc).detach();
    std::thread(&Producter::prouct,pdt).detach();

    while(1)
    {
        this_thread::sleep_for(chrono::seconds(1000));
    }
    return 0;
}

结论

condition.wait如果条件符合将会一直阻塞在这里,直到有notify_one或notify_all去唤醒,才会重新检查条件,符合将继续阻塞,不符合将往下执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值