QT實現(xiàn)多線程兩種方式案例詳解
Qt線程
Qt4.7之前版本處理步驟
1.自定義一個類,繼承于QThread。
class MyThread:public QThread{ public: vid run(); //虛函數(shù) 線程處理函數(shù)(和主線程不在同一個線程) signals: void isDone(); //信號 線程執(zhí)行完發(fā)送 } void MyThread::run() { // 實現(xiàn) -- 復(fù)雜的處理過程 emit isDome; // 發(fā)送線程 };
2.定義線程
MyThread thread;
3.開啟線程
thread.start();
不能通過直接調(diào)用run()函數(shù),通過start()函數(shù)間接調(diào)用run()函數(shù)。
4.自定義線程結(jié)束槽函數(shù)
public: void dealDone(); —————————————————————— void Widget::dealDone(){ // 線程結(jié)束后的操作 }
5.綁定線程結(jié)束信號和線程結(jié)束槽
connect(&thread,&MyThread::isDone,this,&Widget::dealDone);
6.定義線程關(guān)閉槽函數(shù)
void Widget::stopThread(){ // 停止線程 thread->quit(); // 等待線程運行完成之后結(jié)束 thread->wait(); }
建議不要使用terminate()容易出現(xiàn)內(nèi)存問題
建議使用quit()
7.綁定窗口關(guān)閉信號和線程關(guān)閉槽函數(shù)
connect(this,&Widget::destroyed,this,&Widget::stopThread);
新用法處理步驟
1.設(shè)定一個類,繼承于QObject。
2.類中設(shè)置一個線程函數(shù)(只有一個函數(shù)是線程函數(shù))和線程開始信號。
class MyThread : public QObject { Q_OBJECT public: explicit MyThread(QObject *parent = nullptr); void run(); void start(); void stop(); signals: void myThreadrun(); private: bool isrun; public slots: }; void MyThread::run(){ while(isrun == true) { QThread::sleep(1); emit myThreadrun(); qDebug() << "子線程:" << QThread::currentThread(); if(isrun == false) break; } } void MyThread::start() { qDebug() << "開始"; this->isrun = true; } void MyThread::stop(){ qDebug() << "停止"; this->isrun = false; }
3.創(chuàng)建線程對象(不能指定對象)和 QThread子線程對象
MyThread *mythread; QThread *thread; ------------------------------------------------------------------------------------------- this->mythread = new MyThread; this->thread = new QThread(this);
4.處理事件、鼠標按下開啟和關(guān)閉事件、窗口關(guān)閉事件處理
void Widget::dealThread() { static int i = 0; i++; ui->lcdNumber->display(i); } void Widget::on_pushButton_strat_clicked() { if(thread->isRunning() == true){ return; } thread->start(); mythread->start(); emit runThread(); } void Widget::on_pushButton_stop_clicked() { if(thread->isRunning() == false){ return; } mythread->stop(); thread->quit(); thread->wait(); } void Widget::dealThreadclose() { on_pushButton_stop_clicked(); delete mythread; }
5.把自定義線程類加到子線程
mythread->moveToThread(thread);
connect(mythread,&MyThread::myThreadrun,this,&Widget::dealThread);
6. 啟動子線程,只是把線程啟動了,并沒有啟動線程處理函數(shù)。 ```C++ connect(mythread,&MyThread::myThreadrun,this,&Widget::dealThread); connect(this,&Widget::runThread,mythread,&MyThread::run); qDebug() << "主線程:" << QThread::currentThread(); connect(this,&Widget::destroyed,this,&Widget::dealThreadclose);
到此這篇關(guān)于QT實現(xiàn)多線程兩種方式案例詳解的文章就介紹到這了,更多相關(guān)QT實現(xiàn)多線程兩種方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++20 新特性 協(xié)程 Coroutines(2)
上篇文章簡單給大介紹了 C++20 特性 協(xié)程 Coroutines co_yield 和 co_return 那么這篇文章繼續(xù)給大家介紹C++20 的新特性協(xié)程 Coroutines co_await,需要的朋友可以參考一下2021-10-10