Is it safe to emit a signal on an object from another thread (if the slot is connected as QueuedConnection)? I couldn't find a specific piece of documentation that would mention this, the most relevant quote I found is this:
QObject is reentrant. Most of its non-GUI subclasses, such as QTimer, QTcpSocket, QUdpSocket and QProcess, are also reentrant, making it possible to use these classes from multiple threads simultaneously. Note that these classes are designed to be created and used from within a single thread; creating an object in one thread and calling its functions from another thread is not guaranteed to work.
This suggest that it might not be OK, does this also apply to signals? There is a QMutexLocker inside QMetaObject::activate, so it looks to me that it might be thread safe...?
#include <QCoreApplication>
#include <QTimer>
#include <thread>
#include <iostream>
struct Foo : public QObject
{
Q_OBJECT
public:
Foo(QObject* parent) : QObject(parent) {}
public slots:
void run()
{
connect(this, &Foo::signal, this, [] { std::cout << "activated"; }, Qt::QueuedConnection);
std::thread t([this] { emit signal(); });
if (t.joinable()) t.join();
}
signals:
void signal() const;
};
#include "main.moc"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Foo* b = new Foo(&a);
QTimer::singleShot(0, b, &Foo::run);
return a.exec();
}