QT继承QObject以实现多线程功能

QT继承QObject以实现多线程功能

主要利用moveToThread()函数实现线程转移从而实现多线程功能:
(1)创建一个新线程

if(m_objThread1)//判断线程是否已经创建
{
    return;
}
m_objThread1= new QThread();//创建一个新线程
m_obj1 = new ThreadObject();//创建自定义的类指针
m_obj1->SetMutex(&mutex);//设置线程mutex互斥锁
m_obj1->moveToThread(m_objThread1);//将自定义的类(包含需要费时占资源处理的事件)转移到新线程
connect(m_objThread1,SIGNAL(finished()),m_objThread1,SLOT(deleteLater()));//线程结束后调用deleteLater来销毁分配的内存
connect(m_objThread1,SIGNAL(finished()),m_obj1,SLOT(deleteLater()));
connect(this,SIGNAL(startObjThreadWork2()),m_obj1,SLOT(runSomeBigWork2()));//连接新线程中的处理事件的函数
m_objThread1->start();//启动线程

自定义类头文件

#ifndef THREADOBJECT_H
#define THREADOBJECT_H

#include 
#include 
#include 

class ThreadObject : public QObject
{
    Q_OBJECT
public:
    ThreadObject(QObject* parent = NULL);
    ~ThreadObject();
    void stop(QThread *a);
    void SetMutex(QMutex *a);
    bool m_isStop;
public slots:
    void runSomeBigWork1();
    void runSomeBigWork2();
private:
    QMutex *m_stopMutex;
};
#endif // THREADOBJECT_H

主窗口头文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 

#include "threadobject.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_3_clicked();

    void on_pushButton_4_clicked();

    void on_pushButton_5_clicked();

    void on_pushButton_6_clicked();

signals:
    void startObjThreadWork1();
    void startObjThreadWork2();

private:
    void StartThread();
    void StartThread1();

    Ui::MainWindow *ui;

    ThreadObject* m_obj,*m_obj1;
    QThread* m_objThread,* m_objThread1;
};

#endif // MAINWINDOW_H

(2)运行效果
QT继承QObject以实现多线程功能_第1张图片
源代码下载连接:
https://download.csdn.net/download/qq_42755842/12483895

你可能感兴趣的:(Qt,qt,多线程)