【Qt学习】09 Qt多线程之QWaitCondition

概述

学习内容:多线程QWaitCondition的使用。

 

环境

IDE:Qt creator 4.11.0

编译器:MinGW 5.3.0 32bit for C++

 

例子

功能:验证QWaitCondition类中wakeOne与wait函数的用法。

下列代码仅供参考。

1、mythreada.h

#ifndef MYTHREADA_H
#define MYTHREADA_H

#include 
#include 
#include 
#include 
#include 

class MyThreadA : public QThread
{
    Q_OBJECT

public:
    MyThreadA();

public:
    void run();
    void wakeFunc();

private:
    QWaitCondition m_wait;
    QMutex m_mutex;
    MyThreadB m_ThreadB;
    QString m_qstrLog;

};

#endif // MYTHREADA_H

 

2、mythreada.cpp

#include "mythreada.h"

MyThreadA::MyThreadA()
{

}

void MyThreadA::run()
{
    static int x = 0;

    qDebug() << "Thread A run()";

    while (true)
    {
        qDebug() << "------> 1 <------";
        m_mutex.lock();

        x ++;
        if (x > 3)
        {
            m_ThreadB.start();
        }

        m_qstrLog = QString("x = %1").arg(x);
        qDebug() << m_qstrLog;

        m_wait.wait(&m_mutex);
        m_mutex.unlock();

        qDebug() << "------> 2 <------";
    }

}

void MyThreadA::wakeFunc()
{
    if (!isRunning())
    {
        start();
    }
    else
    {
        m_wait.wakeOne();
    }
}

 

3、mythreadb.h

#ifndef MYTHREADB_H
#define MYTHREADB_H

#include 
#include 

class MyThreadB : public QThread
{
    Q_OBJECT
public:
    MyThreadB();

public:
    void run();
};

#endif // MYTHREADB_H

 

4、mythreadb.cpp

#include "mythreadb.h"

MyThreadB::MyThreadB()
{

}

void MyThreadB::run()
{
    qDebug() << "Thread B ia active.";
}

 

5、mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_pThreadA = new MyThreadA();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    qDebug() << "Button clicked.";
    m_pThreadA->wakeFunc();
}

 

总结

1、运行效果如下图所示。

【Qt学习】09 Qt多线程之QWaitCondition_第1张图片

 

2、调试信息

Button clicked.
Thread A run()
------> 1 <------
"x = 1"
Button clicked.
------> 2 <------
------> 1 <------
"x = 2"
Button clicked.
------> 2 <------
------> 1 <------
"x = 3"
Button clicked.
------> 2 <------
------> 1 <------
"x = 4"
Thread B ia active.

3、知识点

m_wait.wait(&m_mutex);

相当于 

m_mutex.unlock();
m_wait.wait(); //线程处于阻塞状态等待信号 注意(unlock和wait是原子的)
m_mutex.lock();

4、代码下载

地址:https://download.csdn.net/download/sunriver2000/12663139

你可能感兴趣的:(Qt,学习)