I have two thread inherited from QThread. The scenario is object of thread2 emit a signal and object of thread1 have a slot to execute. I expected that slots executes in the thread2 but it executes in the Main thread!!!. Here is my sample code to show that:
Headrs.h
class Thread1 : public QThread{
Q_OBJECT
public:
Thread1(){}
protected:
void run(){
qDebug() << "run in thread " << this->currentThreadId();
exec();
}
private slots:
void slot1(){
qDebug() << "slot in " << this->currentThreadId();
}
signals:
void sig1();
};
class Thread2 : public QThread{
Q_OBJECT
protected:
void run(){
msleep(100);
qDebug() << "emit sig2 in: " << this->currentThreadId();
emit sig2();
}
signals:
void sig2();
};
class obj1 : public QObject {
Q_OBJECT
public:
obj1(){
connect(&t2, SIGNAL(sig2()), &t1, SLOT(slot1()));
connect(this, SIGNAL(sigObj()), &t1, SLOT(slot1()));
t1.start();
t2.start();
}
public:
void fcn(){
QThread::msleep(1000);
emit sigObj();
qDebug() << "emit sigObj in " << QThread::currentThreadId();
}
private:
Thread1 t1;
Thread2 t2;
signals:
void sigObj();
};
Main.cpp
QCoreApplication a(argc, argv);
obj1 o1;
o1.fcn();
return a.exec();
What I do expect from this code is to slot1() always execute in thread1 from both emitted signals sig2() and sigObj(). But no matter in what thread we emit the signal, slot1 executes in the main thread. By the way here is my output:
run in thread 0x7ffff6169700 (thread1)
emit sig2 in: 0x7ffff5968700 (thread2)
slot in 0x7ffff7fce740 (main thread)
emit sigObj in 0x7ffff7fce740 (main thread)
slot in 0x7ffff7fce740 (main thread)
Is it something is wrong or always it works like that? And what should I do if I want execute slots in their own threads?