线程同步QSemaphore

QSemaphore类提供了强壮的整数信号量。
QSemaphore也可以被用来使线程的执行顺序化,和QMutex的方法相似。信号量和互斥量的不同在于,信号量可以在同一时间被多于一个的线程访问。

/*
*一个生产者 多个消费者情况,,使用 QSemaphore线程同步
*
*/

#include <QCoreApplication>
#include <thread>
#include <QSemaphore>
#include <iostream>
#include <QThread>
#include <QMutex>
using namespace std;

int dataSize = 100;
const int buffSize = 10;
int buff[102] = {0};
QSemaphore unUsedCount(buffSize);

QSemaphore usedCount(0);

QMutex mutex1;

int j = 0;

void makeData()
{
    for(int i=0;i<dataSize;i++)
    {
        unUsedCount.acquire();
        buff[i] = i;
        usedCount.release();
    }
}

void usedData()
{
    for(;j<dataSize;)
    {

        usedCount.acquire();
        mutex1.lock();
        cout<<  QThread::currentThreadId() <<"  is used: " <<buff[j] << endl;
        mutex1.unlock();
        unUsedCount.release();
        j++;
        QThread::msleep(1000);
    }

}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    thread *t1 = nullptr;
    t1 = new thread(makeData);
    t1->detach();

    thread *t2 = new thread(usedData);
    t2->detach();
    thread *t3 = new thread(usedData);
    t3->detach();
    thread *t4 = new thread(usedData);
    t4->detach();
    thread *t5 = new thread(usedData);
    t5->detach();

    return a.exec();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值