Q读取终止和亲和力
QThread terminate and affinity
这个例子是用来测试QThread的。主要目标是能够在专用线程中运行一次耗时的阻塞方法,并且能够随时终止和重新启动线程。阻止方法是我们无法控制的第三方库。我知道Qt的文档不鼓励使用QThread::终止,但目前我没有看到任何其他方法。
下面是在专用线程中运行所需的代码的 pseduo 示例。基本上有一种方法可能需要10-15分钟来处理。没有合乎逻辑的地方可以添加 moveToThread 以将亲和力带回 QThread::terminate 上的主线程,或者执行 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)
moveToThread API 在第二次执行 Test::d oWork() 方法时失败。这似乎是因为测试实例与另一个线程(此时终止)具有关联性。然后如何更改相关性?
终止和重新启动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(),而不是使用 terminate。
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- llvm构建器向基本块添加终止符
- 如何使用隔离>终止执行来停止所有线程
- 用于将C++代码转换为 Web 程序集的脚本未终止
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- 终止 QProcess 不会终止子进程
- 运行代码时,c++ 会终止进程
- 检测到堆栈粉碎:已终止 中止(核心已转储)
- 在输入句子时终止 std::out_of_range
- 二进制搜索的终止点
- MPI:检查是否有任何进程已终止
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- 如何改进我的代码,使其不会因超时而终止?(黑客排名挑战)
- while 循环不以哨兵值终止
- C++ 程序不会因为内存而终止
- Q读取终止和亲和力