生产者、消费者问题的互斥锁解决方法

it2026-03-10  2

#include <QCoreApplication> #include <QThread> #include <QTime> #include <QMutex> #include <QDebug> class Work : public QObject { protected: enum {WORKMAXSIZE = 1024}; char work[WORKMAXSIZE]; int freeSize; int tail; int head; QMutex mutex; public: Work() { memset(work, 0, WORKMAXSIZE); freeSize = WORKMAXSIZE; tail = head = 0; } bool product(char ch) { if(freeSize > 0) { qDebug() << "work product current thread: " << QThread::currentThread(); mutex.lock(); work[tail] = ch; tail = (tail + 1) % WORKMAXSIZE; freeSize--; mutex.unlock(); return true; } return false; } bool custom(int &ch) { if(freeSize < WORKMAXSIZE) { qDebug() << "work custom current thread: " << QThread::currentThread(); mutex.lock(); ch = work[head]; head = (head + 1) % WORKMAXSIZE; freeSize++; mutex.unlock(); return true; } return false; } }; Work work; class Productor : public QThread { protected: char randChar() { qsrand(QDateTime::currentDateTime().time().msec()); QThread::msleep(1); int ch = qrand() % 52; return (ch < 26) ? static_cast<char>(ch + 'A') : static_cast<char>(ch - 26 + 'a'); } public slots: void run() { while(1) { qDebug() << "productor current thread: " << QThread::currentThread(); int ch = randChar(); qDebug() << "Productor: ch = " << ch; qDebug() << "Productor: flag = " << work.product(ch); } } }; class Customer : public QThread { public slots: void run() { while(1) { qDebug() << "customer current thread: " << QThread::currentThread(); int ch = -1; qDebug() << "Customer: flag = " << work.custom(ch); qDebug() << "Customer: ch = " << ch; } } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Productor product; Customer custom; product.start(); custom.start(); return a.exec(); }
最新回复(0)