I have an object a created in the main thread, where its signals are connected to slots of another object, b, that also lives in the main thread.
Then I create an object c and move it to a worker thread, where it will periodically access object a through a pointer, change its state and emit its signals.
Here is the code:
(Note: some lines were purposely ignored to keep the example short.)
class A : public QObject
{
Q_OBJECT
friend class C;
signals:
void sigA();
private:
quint8 _m1;
quint8 _m2;
};
class B : public QObject
{
Q_OBJECT
public slots:
void slotB();
};
class C : public QObject
{
Q_OBJECT
public:
C(A* a) : _a{a}, _timer{new QTimer{this}}
{
_timer->setInterval(5);
connect(_timer, &QTimer::timeout, this, &C::doSomeWork);
}
public slots:
void start() { _timer->start(); }
private slots:
void doSomeWork()
{
// update members of `a`
emit _a->sigA();
// ...
}
private:
A* _a;
QTimer* _timer;
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
A* a {new A};
B* b {new B};
QObject::connect(a, &A::sigA, b, &B::slotB);
QThread* worker {new QThread};
C* c {new C{a}};
c->moveToThread(worker);
QObject::connect(worker, &QThread::started, c, &C::start);
worker->start();
return app.exec();
}
I hope a signals, emitted from thread worker, will trigger b slots in the main thread. And I hope I'll have no concurrency problems because a members are 8-bit sized.
But c, that lives in thread worker, will be posting events in the main thread event queue. I am not using any synchronization primitive, so I'm afraid I may run into problems.
Is it OK to use the signal/slot mechanism the way I'm using it in the code example? Is there something I need to worry about?