【Qt学习】08 Qt多线程之QMutex

概述

学习内容:通过使用QMutex互斥量,在两个线程顺序顺序操作全局变量,来验证多线程同步技术。

 

QMutex类提供线程之间的访问序列化。

QMutex的目的是保护对象、数据结构或代码片段,以便一次只能有一个线程访问它(这类似于Java synchronized关键字)。通常最好将互斥锁与QMutexLocker一起使用,因为这样可以很容易地确保锁定和解锁一致地执行。

 

环境

IDE:Qt creator 4.11.0

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

 

例子

功能:线程A中增加we,线程B中增加lcome,打印结果welcome或者lcomewe。

例子代码仅使用QMutex,没有使用QMutexLocker。

下列代码仅供参考。

1、mythreada.h

#ifndef MYTHREADA_H
#define MYTHREADA_H

#include 
#include 
#include 

class MyThreadA : public QThread
{

public:
    MyThreadA();

public:
    void run();
};

#endif // MYTHREADA_H

 

2、mythreada.cpp

#include "mythreada.h"

extern QMutex g_mutex;
extern QByteArray g_gbaWelcome;

MyThreadA::MyThreadA()
{

}

void MyThreadA::run()
{
    qDebug() << "Thread A is starting." << endl;

    g_mutex.lock();
    g_gbaWelcome += 'W';
    sleep(2);
    g_gbaWelcome += 'e';
    g_mutex.unlock();

    qDebug() << "Thread A is exiting." << endl;
}

 

3、mythreadb.h

#ifndef MYTHREADB_H
#define MYTHREADB_H

#include 
#include 
#include 

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

public:
    void run();
};

#endif // MYTHREADB_H

 

4、mythreadb.cpp

#include "mythreadb.h"

extern QMutex g_mutex;
extern QByteArray g_gbaWelcome;

MyThreadB::MyThreadB()
{

}

void MyThreadB::run()
{
    qDebug() << "Thread B is starting." << endl;

    g_mutex.lock();
    g_gbaWelcome += 'l';
    sleep(1);
    g_gbaWelcome += "come";
    g_mutex.unlock();

    qDebug() << "Thread B is exiting." << endl;
}

 

5、mainwindow.cpp

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

QMutex g_mutex;
QByteArray g_gbaWelcome;

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

}

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


void MainWindow::on_pushButton_clicked()
{
    g_gbaWelcome.clear();

    m_a.start();
    m_b.start();

    m_t.start();
    while (m_t.elapsed() < 5000)
    {
        QCoreApplication::processEvents();
    }

    qDebug() << g_gbaWelcome << endl;
    ui->lineEdit->setText(g_gbaWelcome);
}

 

总结

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

【Qt学习】08 Qt多线程之QMutex_第1张图片

2、调试信息

Thread A is starting. 

Thread B is starting. 

Thread A is exiting. 

Thread B is exiting. 

"Welcome" 

3、代码下载

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

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