Qt线程同步操作用QWaitCondition QMutex

时间:2022-11-07 23:48:48

可以看到Qt提供了一个等待事件发生的类QWaitCondition,当条件满足时可以唤醒其它等待的线程。

 写一个类可以在线程间实现同步功能

#ifndef THREADEVENT_H
#define THREADEVENT_H

#include <QWaitCondition>
#include <QMutex>

class ThreadEvent
{
public:
    ThreadEvent(const char* name);
    void postMessage();
    bool waitMessage(unsigned long time = ULONG_MAX);
private:
    QWaitCondition waitConditionM;
    QMutex mutexM;
    char Name[64];
    bool bSatisfiedM;
};

#endif // THREADEVENT_H


 

#include "ThreadEvent.h"

ThreadEvent::ThreadEvent(const char* name)
{
    bSatisfiedM = false;
    strcpy(Name,name);
}

void ThreadEvent::postMessage()
{
    qDebug("ThreadEvent: %s\n",Name);
    mutexM.lock();
    bSatisfiedM = true;
    waitConditionM.wakeAll();
    mutexM.unlock();
}

bool ThreadEvent::waitMessage(unsigned long time)
{
    mutexM.lock();
    bool rtn = true;
    if(bSatisfiedM)
    {
        rtn = true;
    }
    else
    {
        rtn = waitConditionM.wait(&mutexM,time);

    }

    bSatisfiedM = false;
    mutexM.unlock();
    return rtn;
}


用法

 

ThreadEvent tevent;

thread1:
tevent.postMessage();

thread2:
tevent.waitMessage();


不管是thread1先到tevent,还是thread2先到tevent,这个类都可满足要求。