基于Qt5的多线程使用

目录

1、前言

2、使用方法


1、前言

目前Qt的多线程使用大部分分为2种,分别是重写run函数、使用moveToThread函数,本文使用的是第二种方案。仅供个人学习参考。

环境:windows + Qt5.12

2、使用方法

1)、修改.h文件,如下所示。代码中有相关注释

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>
#include <QDebug>
#include <QString>
#include <stdio.h>

namespace Ui {
class MainWindow;
}

class My_thread : public QObject
{

    Q_OBJECT

public slots:
    void My_thread_work();

signals:
    void finish_thread(QString str);        //工作结束信号

};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:

    void on_pushButton_clicked(bool checked);

    void show_text(QString str);
    
private:
    Ui::MainWindow *ui;

    My_thread *My_one_thread;

    QThread usethread;                  //声明一个线程

signals:
    void start_thread();                //工作开始信号
};

#endif // MAINWINDOW_H

2)、修改.c文件,如下所示。代码中有相关注释

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

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

    My_one_thread = new My_thread;
    My_one_thread->moveToThread(&usethread);

    connect(&usethread, &QThread::finished, My_one_thread, &QObject::deleteLater);            //该线程结束时销毁
    connect(My_one_thread, &My_thread::finish_thread, this, &MainWindow::show_text);          //第二个线程结束时发送信号,主线程再动作
    connect(this, &MainWindow::start_thread, My_one_thread, &My_thread::My_thread_work);      //主线程控制第二个线程工作

    usethread.start();
}

MainWindow::~MainWindow()
{
    usethread.quit();
    usethread.wait();
    delete ui;
}

void MainWindow::show_text(QString str)
{
    QString main_thread_ID;
    main_thread_ID.sprintf("main ID :%p \r\n", QThread::currentThread());                   //获取主线程ID
    ui->textEdit->setText(ui->textEdit->toPlainText().append(main_thread_ID));              //打印主线程ID
    ui->textEdit->setText(ui->textEdit->toPlainText().append(str));                         //打印第二个线程ID
}

void MainWindow::on_pushButton_clicked(bool checked)
{
    emit start_thread();                                                                    //按钮控制第二个线程工作
}



/********第二个线程相关函数*********/
void My_thread::My_thread_work()
{
    QString second_thread_ID;
    second_thread_ID.sprintf("second ID :%p \r\n", QThread::currentThread());

    emit finish_thread(second_thread_ID);                                                   //第二个线程发送工作结束信号
}

3)、运行结果

点击下方的start按钮,从运行界面中可以看出TEXT中打印的线程ID不同,说明多线程创建成功,因此将任务繁重的工作放在另外一个线程中是保证主线程工作稳定的方法之一。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值