c/c++语言开发共享QT多线程的使用:moveToThread

QT有两种实现多线程的方法,方法一是“子类化QThread,然后去重写run函数,实现多线程”。方法二是“子类化QObject,然后使用moveToThread函数实现多线程”。由于QT官方推荐使用第二种方法,所以这里主要介绍一下,如何通过子类化QObject去实现多线程。首先,我们写一个继承QObject的类,并且在第一行写上Q_OBJECT,在定义一个子线程实现功能的函数。work.h如下:#ifndef WORK_H#define WORK_H#include <QObject&g

QT有两种实现多线程的方法,方法一是“子类化QThread,然后去重写run函数,实现多线程”。方法二是“子类化QObject,然后使用moveToThread函数实现多线程”。由于QT官方推荐使用第二种方法,所以这里主要介绍一下,如何通过子类化QObject去实现多线程。

#ifndef WORK_H #define WORK_H  #include <QObject> #include <QThread> class Work : public QObject {     Q_OBJECT public:     explicit Work(QObject *parent = nullptr);  signals:  public slots:     void thread_fun();   //定义将在子线程中运行的槽函数 public:  };  #endif // WORK_H 

其次,我们在work.cpp中去完善构造函数与功能函数的代码,代码如下:

#include "work.h" #include <QDebug>  Work::Work(QObject *parent) : QObject(parent) {     qDebug()<<"Work构造函数ID: "<<QThread::currentThreadId(); }  void Work::thread_fun() {     qDebug()<<"子线程功能函数ID:"<<QThread::currentThreadId(); }  

第三步,我们在mainwindow.h中添加各种头文件,然后创建一个signals信号,声明一个线程和刚刚创建的work类。

#ifndef MAINWINDOW_H #define MAINWINDOW_H  #include <QMainWindow> #include <QThread> #include "work.h" namespace Ui { class MainWindow; }  class MainWindow : public QMainWindow {     Q_OBJECT  public:     explicit MainWindow(QWidget *parent = nullptr);     ~MainWindow();  private:     Ui::MainWindow *ui;     QThread *thread_test;     Work *worker;  signals:     void toThread(); };  #endif // MAINWINDOW_H 

最后我们在mainwindow.cpp中,先实例化thread_Test线程和work类,然后连接这个信号与槽函数。并且把work这个类推向子线程,并且打开子线程。代码如下:

#include "mainwindow.h" #include "ui_mainwindow.h"  MainWindow::MainWindow(QWidget *parent) :     QMainWindow(parent),     ui(new Ui::MainWindow) {     ui->setupUi(this);     worker = new Work();     thread_test = new QThread();      connect(this, SIGNAL(toThread()), worker, SLOT(thread_fun() ));     //connect(this, &MainWindow::toThread, worker, &Work::thread_fun);     worker->moveToThread(thread_test);     thread_test->start();       //启动线程     emit toThread();            //发送信号 }  MainWindow::~MainWindow() {     delete ui; } 

通过发送信号toThread(),连接槽函数执行thread_fun()。可以看到最后的输出结果,确实不在同一个线程里面,说明多线程配置是成功的。
QT多线程的使用:moveToThread

c/c++开发分享QT多线程的使用:moveToThread地址:https://blog.csdn.net/suxiang6991/article/details/110149182

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/596671.html

(0)
上一篇 2021年5月8日
下一篇 2021年5月8日

精彩推荐