Qt-UI

Queued Connections

Scoped Lock | | Producer Consumer Example

How to pass the produced soup to a consumer, e.g. to the main thread?

Passing messages between threads is easy with Qt. We simply pass objects through a signal/slot connection via so called queued connections.

Passing a message through a regular slot is done via parametrization:

message sender:

emit signal("message");

message receiver:

public slots:
   void slot(QString &message);

Then the receiver is invoked from the same thread as the sender.

To invoke the receiver on a different thread, we connect the signal and the slot with the option of a queued connection:

connect(sender, SIGNAL(signal(QString &)),
        receiver, SLOT(slot(QString &)),
        Qt::QueuedConnection);

Then a triggered signal in the sender thread has the effect of a copy of the parameters being stored in the event queue. The sender returns immediately after the copy has been posted. The copy is delivered to the receiver when the receiver thread yields to the event loop.

This scheme works as long as

  • The type of the passed parameters is a class with a copy constructor.
  • Either the sender or the receiver have an event loop running.
  • The type of the parameter is known to Qt.

If the data type is unknown we register it before connecting the respective signal:

qRegisterMetaType<type>("type");


Scoped Lock | | Producer Consumer Example

Options: