Qt 多线程开启第二种方法

Qt 多线程开启第二种方法
定义一个继承于QObject的worker类,在worker类中定义一个槽slot函数doWork(),这个函数中定义线程需要做的工作;
在要使用线程的controller类中,新建一个QThread的对象和woker类对象,使用moveToThread()方法将worker对象的事件循环全部交由QThread对象处理;
建立相关的信号函数和槽函数进行连接,然后发出信号触发QThread的槽函数,使其执行工作
直接上代码

#ifndef WORKER_H
#define WORKER_H
#include 
#include
#include


class Worker:public QObject                    //work定义了线程要执行的工作
{
    Q_OBJECT
public:
    Worker(QObject* parent = nullptr){}
public slots:
    void doWork(int parameter)                        //doWork定义了线程要执行的操作
    {
        qDebug()<<"receive the execute signal---------------------------------";
        qDebug()<<"     current thread ID:"<<QThread::currentThreadId();
       for(int i = 0;i!=100000;++i)
       {
        ++parameter;
       }
       qDebug()<<"      finish the work and sent the resultReady signal\n";
       emit resultReady(parameter);           //emit啥事也不干,是给程序员看的,表示发出信号发出信号
    }

signals:
    void resultReady(const int result);               //线程完成工作时发送的信号
};


#endif // WORKER_H

#ifndef CONTROLLER_H
#define CONTROLLER_H
#include 
#include
#include
class Controller : public QObject            //controller用于启动线程和处理线程执行结果
{
    Q_OBJECT
    QThread workerThread;
public:
    Controller(QObject *parent= nullptr);
   ~Controller();
public slots:
    void handleResults(const int rslt)                        //处理线程执行的结果
    {
        qDebug()<<"receive the resultReady signal---------------------------------";
        qDebug()<<"     current thread ID:"<<QThread::currentThreadId()<<'\n';
        qDebug()<<"     the last result is:"<<rslt;
    }
signals:
    void operate(const int);                        //发送信号触发线程
};


#endif // CONTROLLER_H

#include "controller.h"
#include"worker.h"

Controller::Controller(QObject *parent) : QObject(parent)
{
    Worker *worker = new Worker;
    worker->moveToThread(&workerThread);            //调用moveToThread将该任务交给workThread

    connect(this, SIGNAL(operate(const int)), worker, SLOT(doWork(int)),Qt::QueuedConnection);            //operate信号发射后启动线程工作
    connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater,Qt::QueuedConnection);            //该线程结束时销毁
    connect(worker, SIGNAL(resultReady(int)), this, SLOT(handleResults(int)),Qt::QueuedConnection);            //线程结束后发送信号,对结果进行处理

   workerThread.start();                //启动线程
    qDebug()<<"emit the signal to execute!---------------------------------";
    qDebug()<<"     current thread ID:"<<QThread::currentThreadId()<<'\n';
    emit operate(0);

   //   workerThread.start();                //启动线程
}

Controller::~Controller()        //析构函数中调用quit()函数结束线程
{
    workerThread.quit();
    workerThread.wait();
}

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