I have two objects which lives in different threads and I'm trying to figure if a pattern used is thread safe or not.
The first object is QObject-derived and lives (was created in) the main Qt thread. The class contains some Q_INVOKABLE methods that should be called from QML, some signal*() methods defined as signals: and some Emit*() (normal) methods that I use as wrappers to emit signals. For example:
void MyQObjectClass::EmitStatus(void) {
emit signalStatusChange(_status);
}
I normally listen for those signals in QML.
The second object is not QObject-derived and lives in a second thread (pthread). This thread runs its own event loop (libev) and dispatches events. I can't use anything related to Qt in this thread because I need the custom libev event loop. On this object I defined some Notify*() methods that will send async events through libev to be picked up by callbacks.
I need to be able to communicate between the two objects/threads, but I'm not sure how to safely do this.
The actual design is to let the pthread thread object call the different Emit*() methods directly so that the QObject can properly propagate the information to Qt/QML. If I need to send information from Qt/QML to the pthread/libev object I call (from the Qt thread) the Notify*() methods.
When reading Accessing QObject Subclasses from Other Threads, it says:
QObject and all of its subclasses are not thread-safe. This includes the entire event delivery system.
but then further it is stated that:
On the other hand, you can safely emit signals from your QThread::run() implementation, because signal emission is thread-safe.
So my question is, is the design described above thread-safe? Can I safely call myQObject->EmitMySignal(), which in turns will call emit signalMySignal(), all this from inside the pthread object?
postEventrather than directly accessing theQObjectlike that.postEventis thread safe and is designed for this purpose if you don't want to or cannot use normal signal/slot connection. - Resurrection_status, if it is accessed from multiple threads. Calling a QObject methods from multiple threads is error prone, so if you do it I recommend a few things: 1. divide the methods into "called from other threads" and "normal" methods, and have distinct naming convention for these. 2. divide the member variables the same way, and be sure to mutex-protect the access to member variables which are meant to be used from multiple threads. 3. Review the code! - hyde