C++多线程——生产者消费者模型
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <deque>
#include <queue>
#include <condition_variable>
using namespace std;
class AA
{
mutex m_mutex;
condition_variable m_cond;
queue<string> m_q;
public:
void incache(int num)
{
cout << this_thread::get_id() << " 生产者申请加锁..." << endl;
lock_guard<mutex> lock(m_mutex);
cout << this_thread::get_id() << " 生产者申请加锁成功..." << endl;
for (int ii = 0; ii < num; ii++)
{
static int bh = 1;
string message = to_string(bh++) + "号turtle";
m_q.push(message);
}
m_cond.notify_all();
}
void outcache()
{
while (true)
{
cout << this_thread::get_id() << " 申请加锁..." << endl;
unique_lock<mutex> lock(m_mutex);
cout << this_thread::get_id() << " 申请加锁成功..." << endl;
while (m_q.empty())
{
cout << this_thread::get_id() << " 等待被唤醒..." << endl;
m_cond.wait(lock);
cout << this_thread::get_id() << " 被唤醒..." << endl;
}
lock.unlock();
string message = m_q.front(); m_q.pop();
this_thread::sleep_for(chrono::milliseconds(1));
cout << "线程:" << this_thread::get_id() << "," << message << endl;
}
}
};
int main()
{
AA aa;
thread t1(&AA::outcache, &aa);
thread t2(&AA::outcache, &aa);
thread t3(&AA::outcache, &aa);
cout << "即将开始生产第一波数据......" << endl;
this_thread::sleep_for(chrono::seconds(5));
aa.incache(3);
this_thread::sleep_for(chrono::seconds(1));
cout << "即将开始生产第二波数据......" << endl;
this_thread::sleep_for(chrono::seconds(5));
aa.incache(5);
t1.join();
t2.join();
t3.join();
}