
Originally Posted by
kachofool
I have a quick question regarding the start up of a new thread, separate to the main thread, and executing a slot in it, from a signal invoked from the main GUI thread. I understand this behaviour is not normally recommended.
It's fine.
I just wanted to know if using moveToThread is the right way to do this (what if the thread quits or is terminated?)
Moving the thread controller to the thread it controls is ok. If the thread quits, the object will probably go back under control of the thread that spawned the child thread in the first place (although that's just my assumption). If you want to do it another way then there is a very easy way to do it. In run() create an object of a new class that will contain the slot you want executed (instead of placing the slot where you have it now - in the thread class).
Here is an example:
class SolutionBringer
: public QObject { Q_OBJECT
public:
//...
public slots:
void MyThreadSlot() { ... }
};
Q_OBJECT
public:
// ...
void run() {
SolutionBringer bringer;
connect(this, SIGNAL(TriggerThread()), &bringer, SLOT(MyThreadSlot()));
emit ready();
exec();
}
signals:
void TriggerThread();
void ready();
};
// ...
Thread *thread = new Thread(...);
connect(obj, SIGNAL(TriggerThread()), thread, SIGNAL(TriggerThread()));
connect(thread, SIGNAL(ready()), &loop, SLOT(quit()));
thread->start();
loop.exec(); // wait until the thread signals it started its work
// ...
class SolutionBringer : public QObject {
Q_OBJECT
public:
//...
public slots:
void MyThreadSlot() { ... }
};
class Thread : public QThread {
Q_OBJECT
public:
// ...
void run() {
SolutionBringer bringer;
connect(this, SIGNAL(TriggerThread()), &bringer, SLOT(MyThreadSlot()));
emit ready();
exec();
}
signals:
void TriggerThread();
void ready();
};
// ...
Thread *thread = new Thread(...);
connect(obj, SIGNAL(TriggerThread()), thread, SIGNAL(TriggerThread()));
QEventLoop loop;
connect(thread, SIGNAL(ready()), &loop, SLOT(quit()));
thread->start();
loop.exec(); // wait until the thread signals it started its work
// ...
To copy to clipboard, switch view to plain text mode
Bookmarks