Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Object members in another QThread

I have 2 Threads in a Qt5Application:

Thread A: contains a bunch of QObject derived class objects

Thread B: worker in this Thread has all the pointers to the objects in A

Thread A might be very busy at times and Thread B is only there to delegate Signals and manage some other stuff. It never writes to any of these objects, but I need to check some getter functions which return booleans from the objects in A.

in ThreadB:
if (objInThrA->isFinished()) { ... }

The isFinished() returns a boolean.

If Thread A is really busy in a function and I call these isFinished functions in Thread B, will my Thread B get stalled until Thread A is finished with its work, or will this work?

like image 855
Mindcode Avatar asked Mar 08 '15 09:03

Mindcode


People also ask

Is QObject thread-safe?

QObject and all of its subclasses are not thread-safe. This includes the entire event delivery system. It is important to keep in mind that the event loop may be delivering events to your QObject subclass while you are accessing the object from another thread.

Are Qt signals and slots thread-safe?

It is generally unsafe to provide slots in your QThread subclass, unless you protect the member variables with a mutex. On the other hand, you can safely emit signals from your QThread::run() implementation, because signal emission is thread-safe.

Is Qt multithreaded?

Qt offers many classes and functions for working with threads. Below are four different approaches that Qt programmers can use to implement multithreaded applications.

How do you use QThread?

To use it, prepare a QObject subclass with all your desired functionality in it. Then create a new QThread instance, push the QObject onto it using moveToThread(QThread*) of the QObject instance and call start() on the QThread instance. That's all.


1 Answers

Qt signals and slots can be used between different threads. But there are two rules:

  1. Last argument of connect() should be either Qt::QueuedConection or Qt::BlockingQueuedConnection (or defaults to Qt::AutoConnection, which is the same as Qt::QueuedConnection if objects belong to different threads). QueuedConnection means that emitter does not wait signal processing to be completed, BlockingQueuedConnection means it does.

  2. QObject-derived classes are not suitable for passing between threads. They should be safely copied before that (see QMetaType docs).

like image 76
Matt Avatar answered Oct 05 '22 16:10

Matt