Qt中条件等待、异步转同步方式整理

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

// Qt中条件等待、异步转同步方式整理
class ThreadTest : public QThread
{
    Q_OBJECT
public:
    explicit ThreadTest(QObject *parent = nullptr) : QThread(parent){}
    void run() override
    {
        m_stop = false;
        qDebug()<<"void run() override start";
        // 1. QTime
        m_time.restart();
        while ( !m_stop && m_time.elapsed() < m_waitInterval )
        {
            msleep(20);
        }

        // 2. QEventLoop
        m_loop = new QEventLoop;
        QTimer::singleShot(m_waitInterval, m_loop, SLOT(quit()));
        m_loop->exec();

        // 3. QWaitCondition
        m_mutex.lock();
        m_condition.wait(&m_mutex, m_waitInterval);
        m_mutex.unlock();

        qDebug()<<"void run() override end";
    }

    Q_INVOKABLE void stop()
    {
        m_stop = true;
        m_loop->quit();
        m_condition.wakeAll();
    }

private:
    bool m_stop;
    const int m_waitInterval = 5000;
    QTime m_time;
    QEventLoop *m_loop;
    QMutex m_mutex;
    QWaitCondition m_condition;
};

你可能感兴趣的:(笔记,qt5,c++)