日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

qt 等待线程结束_c – 停止Qt线程:调用exit()或quit()不会停止线程执行

發布時間:2025/3/15 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 qt 等待线程结束_c – 停止Qt线程:调用exit()或quit()不会停止线程执行 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在main()即主線程中創建了一個QThread.

將一個worker類移動到新線程.該線程執行worker類的’StartThread’方法.

工人線程:

//header file

class Worker : public QObject

{

Q_OBJECT

public:

Worker(QThread* thread);

public slots:

void StartThread();

void EndThread();

private:

QThread* m_pCurrentThread;

};

// source file

#include "QDebug"

#include "QThread"

#include "worker.h"

Worker::Worker(QThread* thread)

{

m_pCurrentThread = thread;

}

void Worker::StartThread()

{

qDebug() << " StartThread";

while(true)

{

QThread::msleep(1000);

qDebug() << " thread running";

static int count = 0;

count++;

if(count == 10)

{

break;

}

if(m_pCurrentThread->isInterruptionRequested())

{

qDebug() << " is interrupt requested";

// Option 3:

m_pCurrentThread->exit();

}

}

qDebug() << "StartThread finished";

}

void Worker::EndThread()

{

qDebug() << "thread finished";

}

Main.cpp的

#include

#include "worker.h"

#include "QThread"

#include "QObject"

#include "QDebug"

int main(int argc, char *argv[])

{

QCoreApplication a(argc, argv);

QThread* thread = new QThread();

Worker* workerObj = new Worker(thread);

QObject::connect(thread,

SIGNAL(started()),

workerObj,

SLOT(StartThread()));

QObject::connect(thread,

SIGNAL(finished()),

workerObj,

SLOT(EndThread()));

workerObj->moveToThread(thread);

thread->start();

thread->requestInterruption();

QThread::msleep(2000);

qDebug() << "terminate thread";

if(thread->isRunning())

{

// Option 1,2 exit() / quit() used but got same output

thread->exit();

qDebug() << "wait on thread";

thread->wait();

}

qDebug() << " exiting main";

return a.exec();

}

現在,在’StartThread’完成并正常退出線程之前,我想從主線程中停止線程.

用過的,

> thread-> exit()

并在主線程中等待(thread-> wait()).

> thread-> quit()

并在主線程中等待(thread-> wait()).

>’StartThread’中的exit()

預期:

一旦從主線程調用exit()/ quit(),線程執行就應該停止.

實際:

在所有三個實例中,線程一直在運行,完成’StartThread’方法并正常退出.盡管沒有調用exit()/ quit().

輸出:

StartThread

thread running

is interrupt requested

terminate thread

wait on thread

thread running

is interrupt requested

thread running

is interrupt requested

thread running

is interrupt requested

thread running

is interrupt requested

thread running

is interrupt requested

thread running

is interrupt requested

thread running

is interrupt requested

thread running

is interrupt requested

thread running

StartThread finished

thread finished

exiting main

是否可以在主線程需要時停止/處理線程?

總結

以上是生活随笔為你收集整理的qt 等待线程结束_c – 停止Qt线程:调用exit()或quit()不会停止线程执行的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。