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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM