• Qt线程同步操作用QWaitCondition QMutex


    可以看到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
    ",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,这个类都可满足要求。

  • 相关阅读:
    理解SetCapture、ReleaseCapture、GetCapture(控制了消息发往哪个窗口,是理解消息的关键)
    Javascript 的addEventListener()及attachEvent()区别分析
    鼠标拖拽
    鼠标右键菜单
    keydown
    一串跟随鼠标的DIV
    event对象和事件冒泡
    发表说说
    文档流
    CSS3 @keyframes 规则
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3144756.html
Copyright © 2020-2023  润新知