• Qt 多线程QThread实现方法之一


    基本思想

    1. 在主线程中,哪里需用多线程,就在哪里创建一个QThread实例;
    2. 把耗时操作封装到一个继承于QObject的子类(这里叫做工作类Worker)槽函数中;
    3. 创建QThread实例和Worker实例,建立他们之间的信号和槽关系;
    4. 调用Worker实例的moveToThread(QThread * thread)函数,将它移动到创建的QThread线程中去;
    5. 最后,执行QThread线程的start()方法。

    工作类

    worker.h

     1 #ifndef WORKER_H
     2 #define WORKER_H
     3 #include <QObject>
     4 class Worker : public QObject
     5 {
     6     Q_OBJECT
     7 public:
     8     explicit Worker(QObject *parent = 0);
     9 signals:
    10     void complete();
    11 public slots:
    12     void doLongTimeWork();//耗时操作
    13 };
    14 #endif // WORKER_H

    worker.cpp

     1 #include "worker.h"
     2 #include <QDebug>
     3 #include <QThread>
     4 Worker::Worker(QObject *parent) : QObject(parent)
     5 {
     6 
     7 }
     8 void Worker::doLongTimeWork()
     9 {
    10     qDebug()<<__LINE__<<__FUNCTION__<<" - enter";
    11     qint64 count = 100;
    12     while(count--){
    13         QThread::msleep(10);
    14         qDebug()<<__LINE__<<__FUNCTION__<<"count = "<<count;
    15     }
    16     emit complete();
    17     qDebug()<<__LINE__<<__FUNCTION__<<" - leave";
    18 }

    使用方法

     1 void MainWindow::on_pushButtonDoWork_clicked()
     2 {
     3     Worker* worker = new Worker();
     4     QThread* thread = new QThread();
     5     //当线程启动时,执行Worker类的耗时函数doLongTimeWork()
     6     connect(thread,SIGNAL(started()),worker,SLOT(doLongTimeWork()));
     7     //当耗时函数执行完毕,发出complete()信号时,删除worker实例
     8     connect(worker,SIGNAL(complete()),worker,SLOT(deleteLater()));
     9     //当worker对象实例销毁时,退出线程
    10     connect(worker,SIGNAL(destroyed(QObject*)),thread,SLOT(quit()));
    11     //当线程结束时,销毁线程对象实例
    12     connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()));
    13     //移动worker对象实例到线程中
    14     worker->moveToThread(thread);
    15     //启动线程
    16     thread->start();
    17 }
  • 相关阅读:
    Bitnami WordPress如何让默认URL指向WordPress目录?
    单片机调试
    FreeRTOS
    FreeRTOS
    FreeRTOS
    FreeRTOS
    FreeRTOS
    FreeRTOS 问题归纳
    单片机通信的加密和解密
    IAR ------ 扩展关键字__weak
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/12169811.html
Copyright © 2020-2023  润新知