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;
}
至此,便可完成线程同步