我已经阅读了很多关于为什么在大多数情况下子类化QThread
是个坏主意以及如何正确使用QThread
,调用moveToThread
方法的文章。 Here我们可以看到这种设计的典型例子。
我正在设计的课程应符合以下要求:
它想要使用信号和插槽,所以我需要一个事件循环并使用moveToThread
。
它只会向接口显示信号和插槽。没有普通的C ++方法。
所有插槽都应在对象的专用线程中执行,每个对象一个线程。因此,线程应该在创建对象时创建,并且应该在对象死亡时完成。
因此,我们会想到一个明显的解决方案(未经测试,只是草图代码):
class Worker : public QObject {
Q_OBJECT
public:
Worker() {
thread = new QThread();
// ...Some signal-slot connections may be done here...
// ...Some other connections may be performed by user code...
moveToThread(thread);
thread->start();
}
~Worker() {
thread->exit();
thread->wait();
delete thread;
}
public slots:
void process(); // and other interface slots
signals:
// Interface signals
private:
QThread* thread;
};
所以重点是将QThread
对象声明为工人类的(私有)成员,但我从未在任何示例或其他人的代码中看到过这种情况。
这就是为什么我想知道这个设计是否有缺陷?它有一些我没注意到的致命缺点吗?或者没关系,但是经常不需要?
答案 0 :(得分:1)
只要将对象移出工作线程,就可以执行此操作。这里有你怎么做 - 请注意你应该按值保存线程,没有必要使用编译器为你管理内存。
class Worker : public QObject {
Q_OBJECT
QThread m_thread;
public:
Worker() {
m_thread.start();
moveToThread(&m_thread);
}
~Worker() {
// Move us out of any thread.
// moveToThread must always be called from QObject::thread()!
{
QObject sig;
sig.connect(&sig, &QObject::destroyed, this, [this]{
this->moveToThread(0); // become thread-less
m_thread->quit();
});
}
// Wait for the thread to stop
m_thread.wait();
}
};
鉴于可以通过QtConcurrent::run
异步完成工作,您很可能无论如何也不应该使用这样的对象。最有可能的是,您将浪费大多数空闲的线程,因为您不可能始终保持线程可以运行。不可运行的线程本质上是一种浪费的资源。