这里写自定义目录标题
基于C++的生产者和消费者实现:
- std::condition_variable简单实用;
- 随机数简单使用;
- 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去唤醒,才会重新检查条件,符合将继续阻塞,不符合将往下执行