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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值