#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();
}
生产者、消费者问题的互斥锁解决方法
最新推荐文章于 2025-03-20 17:08:59 发布
该博客展示了如何使用C++的QThread、QMutex等类实现一个多线程环境下的生产者-消费者模型。代码中定义了一个工作类Work,包含产品生产和消费的方法,并通过互斥锁mutex保证线程安全。Productor类作为生产者线程不断生成随机字符并存入工作队列,Customer类作为消费者线程从队列中取出字符。整个程序演示了并发编程中的同步和通信机制。

3709

被折叠的 条评论
为什么被折叠?



