C++实现
//.h
#ifndef PCMAINWINDOW_H
#define PCMAINWINDOW_H
#include <QMainWindow>
#include <thread>
class PCMainWIndow : public QMainWindow
{
Q_OBJECT
public:
explicit PCMainWIndow(QWidget *parent = nullptr);
signals:
private:
QList<QObject*> * m_pList;
std::condition_variable m_cond;
std::condition_variable m_cond2;
std::mutex m_mutex;
};
#endif // PCMAINWINDOW_H
#include "pcmainwindow.h"
#include <thread>
#include <QPushButton>
#include <QDebug>
#include <mutex>
PCMainWIndow::PCMainWIndow(QWidget *parent)
: QMainWindow{parent},
m_pList(nullptr)
{
m_pList = new QList<QObject*>();
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_lock<std::mutex> mt(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_lock<std::mutex> mt(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 ();
}