在 Qt 中,当线程结束时对象会发生什么?
In Qt, what happens to an object when a thread finishes?
我有一个简单的QObject
:
class Engine : public QObject
{
Q_OBJECT
public:
explicit Engine(QObject* parent = 0);
signals:
void finished();
public slots:
void start();
};
实例 Engine* engine
存储在主 window class 中。按下按钮时,会发生以下情况:
QThread* thread = new QThread;
engine->moveToThread(thread);
connect(engine, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), engine, SLOT(start()));
connect(engine, SIGNAL(finished()), thread, SLOT(quit()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
我的问题是,thread
完成后 engine
会怎样?我可以创建另一个线程并将 engine
移动到该线程,然后再次重复所有内容吗?
What happens to engine after thread finishes?
对象发生的事情与它被移动到线程无关。当您 "move" 时,您并没有真正采取行动,您只是告诉您在线程上执行一些代码。该对象将像往常一样被销毁(超出范围或删除分配的堆)。
Can I create another thread and move engine to that thread, and repeat
everything again?
可以,只要对象还存在。
我有一个简单的QObject
:
class Engine : public QObject
{
Q_OBJECT
public:
explicit Engine(QObject* parent = 0);
signals:
void finished();
public slots:
void start();
};
实例 Engine* engine
存储在主 window class 中。按下按钮时,会发生以下情况:
QThread* thread = new QThread;
engine->moveToThread(thread);
connect(engine, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), engine, SLOT(start()));
connect(engine, SIGNAL(finished()), thread, SLOT(quit()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
我的问题是,thread
完成后 engine
会怎样?我可以创建另一个线程并将 engine
移动到该线程,然后再次重复所有内容吗?
What happens to engine after thread finishes?
对象发生的事情与它被移动到线程无关。当您 "move" 时,您并没有真正采取行动,您只是告诉您在线程上执行一些代码。该对象将像往常一样被销毁(超出范围或删除分配的堆)。
Can I create another thread and move engine to that thread, and repeat everything again?
可以,只要对象还存在。