
Originally Posted by
prof.ebral
Hmmm, I thought the main thread received the signal as a handler and then executed the method defined by the slot.
No, it depends on the thread affinity of the object that the slot belongs to. Here is a simple example:
#include <QtCore>
Q_OBJECT
public:
}
public slots:
void reportThread() {
qDebug
() << Q_FUNC_INFO <<
QThread::currentThread();
}
};
#include "main.moc"
int main(int argc, char **argv) {
QVector<QThread*> threads;
QVector<Object*> objects;
for(int i=0;i<4;++i) {
threads << thr;
Object *o = new Object;
o->moveToThread(thr);
objects << o;
thr->start();
}
// last object in main thread
objects << new Object;
qDebug() << "GUI thread:" << objects.last()->thread();
t.start(2000);
foreach(Object *o, objects)
QObject::connect(&t,
SIGNAL(timeout
()), o,
SLOT(reportThread
()));
return app.exec();
}
#include <QtCore>
class Object : public QObject {
Q_OBJECT
public:
Object(QObject *parent = 0) : QObject(parent) {
}
public slots:
void reportThread() {
qDebug() << Q_FUNC_INFO << QThread::currentThread();
}
};
#include "main.moc"
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
QVector<QThread*> threads;
QVector<Object*> objects;
for(int i=0;i<4;++i) {
QThread *thr = new QThread;
threads << thr;
Object *o = new Object;
o->moveToThread(thr);
objects << o;
thr->start();
}
// last object in main thread
objects << new Object;
qDebug() << "GUI thread:" << objects.last()->thread();
QTimer t;
t.start(2000);
foreach(Object *o, objects)
QObject::connect(&t, SIGNAL(timeout()), o, SLOT(reportThread()));
return app.exec();
}
To copy to clipboard, switch view to plain text mode
You can also move the timer to one of the threads and see if it changes anything.
Oh, one more thing -- you can run this example under a debugger, set a breakpoint in the slot and look at the backtrace. You'll see how it differs for the last added object (the one that lives in the main thread) compared to other objects.
Bookmarks