【无标题】

Qt线程同步问题

需求

描述:
现在有一个任务,需要做若干次(举例4次)。且这4次任务分配到4个线程中。
这4个线程需要到达某一个地方同步一下,然后让其中一个线程执行某个步骤(其它线程不用执行了)
其它3个线程等待它完成这个步骤后,4个线程再一起执行后续其它任务

如图
线程同步问题
Qt代码如下
Worker.h

#ifndef WORKER
#define WORKER

#include <QObject>
#include <qmutex.h>
#include <qwaitcondition.h>
#include <qdebug.h>
#include <qthread.h>
#include <atomic>
#include <mutex>
#include <iostream>
#include <QMutexLocker>

class Worker : public QObject
{
     Q_OBJECT
public:
    explicit Worker(QObject *parent = nullptr);
    ~Worker();

    void synchronization();
    
signals:
    void sigFinished();

public slots:
    void doWork();
    
private:
    static QWaitCondition   g_waitCondition_synchronizationThread;
    static QMutex           g_mutex_synchronizationThread;
    static QAtomicInt       gn_threadCount;
    static QAtomicInt       gn_completeCount;
    static QMutex           g_mutex_used;
    static std::atomic_bool gb_used;
};

#endif // WORKER

Worker.cpp

#include "worker.h"

QWaitCondition   Worker::g_waitCondition_synchronizationThread;
QMutex           Worker::g_mutex_synchronizationThread;
QAtomicInt       Worker::gn_threadCount = 5;
QAtomicInt       Worker::gn_completeCount = 0;
QMutex           Worker::g_mutex_used;
std::atomic_bool Worker::gb_used;

Worker::Worker(QObject *parent) : QObject(parent)
{
    
}

Worker::~Worker()
{
    qDebug() << QThread::currentThreadId() << "delete";
}

void Worker::synchronization()
{
    g_mutex_synchronizationThread.lock();
    gn_completeCount++;
    if(gn_completeCount == gn_threadCount){
        gn_completeCount = 0;
        g_waitCondition_synchronizationThread.wakeAll();
    }
    else{
        g_waitCondition_synchronizationThread.wait(&g_mutex_synchronizationThread);
    }
    g_mutex_synchronizationThread.unlock();
}

void Worker::doWork()
{
    qDebug() << QThread::currentThreadId() << "do some previous work";
    
    synchronization();
    
    {
        QMutexLocker locker(&g_mutex_used);
        if(!gb_used){
            //没有线程占用资源时,则本线程使用此资源
            gb_used = true;
            qDebug() << QThread::currentThreadId() << "---do some specific work---";
        }
    }
    
    synchronization();
    gb_used = false;
    
    qDebug() << QThread::currentThreadId() << "do some next work";
    emit sigFinished();
    
    return;
}

至此,便可完成线程同步

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wxiangjianhuan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值