[英]QThread terminate and affinity
本示例用於測試QThread。 主要目標是能夠在專用線程中運行一種耗時的阻塞方法,並能夠在任何時候終止和重新啟動線程。 阻止方法是我們無法控制的第三方庫。 我知道Qt的文檔不鼓勵使用QThread :: terminate,但是目前我看不到任何其他方式。
下面是在專用線程中運行所需代碼的pseduo示例。 基本上有一種方法可能需要10到15分鍾才能完成處理。 沒有邏輯上的位置添加moveToThread來使親和力回到QThread :: termination上的主線程,或者執行processEvent來處理QThread :: quit()方法。
void run()
{
// initiate variables
thirdparty lib(var1, var2);
int res = lib.execute(var3, var4, var6);
// handle result and exit
}
在Windows 7上使用Qt 4.7。
運行代碼將產生此輸出
Test::doWork thread: QThread(0x219e960)
Test::started thread: QThread(0x239bce8)
Test::doTerminate thread: QThread(0x239bce8)
Test::doWork thread: QThread(0x239bce8)
QObject::moveToThread: Current thread (0x219e960) is not the object's thread (0x239bce8). Cannot move to target thread (0x239bd20)
在第二次執行Test :: doWork()方法時,moveToThread API失敗。 這似乎是因為Test實例與另一個線程(此時已終止)具有親和力。 然后如何更改親和力?
建議的終止和重新啟動QThread的方法是什么? 我需要刪除測試實例嗎?
編碼;
#include <QCoreApplication>
#include <QThread>
#include <iostream>
#include <QDebug>
#include "Worker.h"
#include "Windows.h"
class Test : public QObject
{
Q_OBJECT
QThread* m_thread;
int m_state;
public:
Test() : m_thread(0), m_state(3) { }
public slots:
void doWork()
{
qDebug() << "Test::doWork thread:" << QObject::thread();
if (!m_thread)
{
m_thread = new QThread();
QObject::moveToThread(m_thread);
QObject::connect(m_thread, SIGNAL(started()), this, SLOT(started()));
QObject::connect(m_thread, SIGNAL(finished()), this, SLOT(finished()));
QObject::connect(m_thread, SIGNAL(terminated()), this, SLOT(terminated()));
m_thread->start();
}
}
void started()
{
qDebug() << "Test::started thread:" << QObject::thread();
Sleep(60);
}
void finished()
{
qDebug() << "Test::finished thread:" << QObject::thread();
}
void terminated()
{
qDebug() << "Test::terminated thread:" << QObject::thread();
}
void doTerminate()
{
qDebug() << "Test::doTerminate thread:" << QObject::thread();
QObject::disconnect(m_thread);
m_thread->terminate();
m_thread->wait();
m_thread = NULL;
}
int state()
{
return m_state;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Test test;
test.doWork();
Sleep(10);
test.doTerminate();
Sleep(10);
test.doWork();
return a.exec();
}
可以使用更可接受的函數quit()代替使用終止方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.