Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

inter-object communication



  • Hi all -

    I've posted about this in the past, but I'd like to pursue it a bit further.

    Let's say you have an app with two threads: a worker and a widget. The worker thread contains objects, and the widget invokes other widgets or dialogs for various tasks.

    One dialog needs to display information contained in an object within worker. What's the most straightforward way of accessing this? In the past, I've passed the address of the widget to the worker at creation, used a call in widget from main() to give it the worker address, and passed this information into the dialog and information objects at creation. Functional, but messy.

    I'm sure there are multiple better ways to do this...any suggestions?

    Thanks...


  • Moderators

    A fully secure solution would be to send a signal from worker thread to main thread, passing the information in signal arguments. This way Qt will ensure that you won't get any data races, slowdowns etc. If data changes, signal is sent again.

    Another solution would be to pass object pointer from worker to main thread. Then you can read the information from that object in your main thread, but you have to make sure the access is secure (use a QMutex or better - QMutexLocker).



  • @sierdzio sorry I'm so late in responding.

    Your points are valid, and your solution is secure, but (I think) it still suffers the complexity of the indirection that I mention in my post. I was hoping for away to reduce this somewhat, as it does make the code a bit less easy to read.


  • Moderators

    I don't think there is a way to simplify. Threads are always complicated, when communication is involved (if there is no IPC, then it does become simpler - you can run tasks with QtConcurrent module, QFutures etc.).

    For some simple tasks, perhaps you can get around some of the complexity by using atomics (https://doc.qt.io/qt-5/qatomicint.html) but it is also a tricky subject.


  • Qt Champions 2017

    My advice is stick to @sierdzio's suggestion. Mixing explicit calls with signals slots isn't for the faint of heart, and if you're using a worker object you pretty much've opted for the signals/slots mechanism. As for atomics - better be really simple, otherwise it's a deep and rather complex subject.



  • OK, thanks for the input, guys. I'll continue with my current method.


Log in to reply