PDA

View Full Version : emit singnals from another thread



danics
7th March 2017, 10:03
Hi everybody!

I want to know if I emit a signal from another thread which event loop is responsible for emitting the signal. in other words, this signal emitted from which thread?

for example mysignal in below code



class O2;

class O1 : public QObject
{
Q_OBJECT
public:
O1(QObject *parent = 0): olocal(new O2(this)), QObject(parent)
{
m_thread = new QThread;
olocal->moveToThread(m_thread);
connect(m_thread, SIGNAL(started()), olocal, SLOT(start()));
connect(olocal, SIGNAL(finished()), m_thread, SLOT(quit()));

....
}

~O1() {
olocal->finish();
m_thread->wait();
delete olocal;
delete m_thread;
}

signals:
void mysignal();
};

class O2 : public QObject
{
Q_OBJECT
public:
O2(O1 *parent) : q_ptr(parent) {}

signals:
void finished();

public slots:
void start() { b_start = true; QTimer::singleShot(0, this, SLOT(run())); }
void finish() { b_finish = true; }

void run() {
if(b_finished) {
emit finished();
return;
}

// do some staff
if( /* something */)
emit q_ptr->mysignal();

if(b_start)
QTimer::singleShot(0, this, run());
}
};



thanks in advance

jefftee
7th March 2017, 15:31
The signal would be emitted from the thread that is executing your code that does the emit. Your connect statements above will used queued connections when the sender/receiver are in different threads. You can force the connection type, but I would recommend that you use the default queued connection type unless you have very specific requirements.

anda_skoa
9th March 2017, 08:18
Just to clarify: there is no event loop involved with emitting
However, with a QueuedConnection the slot it called by the event loop of the thread "owning" the receiver object.

The same is true for an AutoConnection when the thread executing the emit is a different one than the "receiver" thread, as jefftee said.

Cheers,
_