生产者消费者模型-创新互联
生产者消费者模型
名称栏目:生产者消费者模型-创新互联
文章源于:http://lswzjz.com/article/dcpspi.html
- C++实现
//.h
#ifndef PCMAINWINDOW_H
#define PCMAINWINDOW_H
#include#includeclass PCMainWIndow : public QMainWindow
{
Q_OBJECT
public:
explicit PCMainWIndow(QWidget *parent = nullptr);
signals:
private:
QList* m_pList;
std::condition_variable m_cond;
std::condition_variable m_cond2;
std::mutex m_mutex;
};
#endif // PCMAINWINDOW_H
#include "pcmainwindow.h"
#include#include#include#includePCMainWIndow::PCMainWIndow(QWidget *parent)
: QMainWindow{parent},
m_pList(nullptr)
{
m_pList = new QList();
QPushButton * btn = new QPushButton(this);
btn->setGeometry (20,20,50,50);
btn->setText ("生产");
connect (btn,&QPushButton::clicked,this,[&](bool) {
//生产者线程
std::thread([&] {
while (true) {
std::unique_lockmt(m_mutex);
m_cond2.wait (mt,[&]{return m_pList->count ()< 10;});
m_pList->push_back (new QObject());
m_pList->push_back (new QObject());
m_pList->push_back (new QObject());
qDebug()<< "生产数据"<< m_pList->count ();
m_cond.notify_all ();
}
}).detach ();
});
//消费者线程
std::thread([&] {
while (true) {
std::unique_lockmt(m_mutex);
m_cond.wait (mt,[&]{return !(m_pList->isEmpty ());});
m_pList->pop_front ();
qDebug()<< "消费数据"<< m_pList->count ();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (m_pList->count ()< 5) {
m_cond2.notify_all ();
qDebug()<< "通知: 生产数据";
}
}
}).detach ();
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
名称栏目:生产者消费者模型-创新互联
文章源于:http://lswzjz.com/article/dcpspi.html