Qt signal slot main thread

Threads and QObjects

QThread inherits QObject. It emits signals to indicate that the thread started or finished executing, and provides a few slots as well.

More interesting is that QObjects can be used in multiple threads, emit signals that invoke slots in other threads, and post events to objects that "live" in other threads. This is possible because each thread is allowed to have its own event loop.

QObject Reentrancy

QObject is reentrant. Most of its non-GUI subclasses, such as QTimer, QTcpSocket, QUdpSocket and QProcess, are also reentrant, making it possible to use these classes from multiple threads simultaneously. Note that these classes are designed to be created and used from within a single thread; creating an object in one thread and calling its functions from another thread is not guaranteed to work. There are three constraints to be aware of:

  • The child of a QObject must always be created in the thread where the parent was created. This implies, among other things, that you should never pass the QThread object ( this ) as the parent of an object created in the thread (since the QThread object itself was created in another thread).
  • Event driven objects may only be used in a single thread. Specifically, this applies to the timer mechanism and the network module. For example, you cannot start a timer or connect a socket in a thread that is not the object's thread.
  • You must ensure that all objects created in a thread are deleted before you delete the QThread. This can be done easily by creating the objects on the stack in your run() implementation.

Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. They can only be used from the main thread. As noted earlier, QCoreApplication::exec() must also be called from that thread.

In practice, the impossibility of using GUI classes in other threads than the main thread can easily be worked around by putting time-consuming operations in a separate worker thread and displaying the results on screen in the main thread when the worker thread is finished. This is the approach used for implementing the Mandelbrot Example and the Blocking Fortune Client Example.

In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the platform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application should make the QApplication be the first created, and last destroyed QObject.

Per-Thread Event Loop

Each thread can have its own event loop. The initial thread starts its event loop using QCoreApplication::exec(), or for single-dialog GUI applications, sometimes QDialog::exec(). Other threads can start an event loop using QThread::exec(). Like QCoreApplication, QThread provides an exit(int) function and a quit() slot.

An event loop in a thread makes it possible for the thread to use certain non-GUI Qt classes that require the presence of an event loop (such as QTimer, QTcpSocket, and QProcess). It also makes it possible to connect signals from any threads to slots of a specific thread. This is explained in more detail in the Signals and Slots Across Threads section

below.

A QObject instance is said to live in the thread in which it is created. Events to that object are dispatched by that thread's event loop. The thread in which a QObject lives is available using QObject::thread().

The QObject::moveToThread() function changes the thread affinity for an object and its children (the object cannot be moved if it has a parent).

Calling delete on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment. Use QObject::deleteLater() instead, and a DeferredDelete event will be posted, which the event loop of the object's thread will eventually pick up. By default, the thread that owns a QObject is the thread that creates the QObject, but not after QObject::moveToThread() has been called.

If no event loop is running, events won't be delivered to the object. For example, if you create a QTimer object in a thread but never call exec(), the QTimer will never emit its timeout() signal. Calling deleteLater() won't work either. (These restrictions apply to the main thread as well.)

You can manually post events to any object in any thread at any time using the thread-safe function QCoreApplication::postEvent(). The events will automatically be dispatched by the event loop of the thread where the object was created.

Event filters are supported in all threads, with the restriction that the monitoring object must live in the same thread as the monitored object. Similarly, QCoreApplication::sendEvent() (unlike postEvent()) can only be used to dispatch events to objects living in the thread from which the function is called.

Accessing QObject Subclasses from Other Threads

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.

If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior.

Like other objects, QThread objects live in the thread where the object was created -- not in the thread that is created when QThread::run() is called. 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.

Signals and Slots Across Threads

Qt supports these signal-slot connection types:

    (default) If the signal is emitted in the thread which the receiving object has affinity then the behavior is the same as the Direct Connection. Otherwise, the behavior is the same as the Queued Connection." The slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread. The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread. The slot is invoked as for the Queued Connection, except the current thread blocks until the slot returns.

Note: Using this type to connect objects in the same thread will cause deadlock.

The connection type can be specified by passing an additional argument to connect(). Be aware that using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, for the same reason that calling any function on an object living in another thread is unsafe.

The Mandelbrot Example uses a queued connection to communicate between a worker thread and the main thread. To avoid freezing the main thread's event loop (and, as a consequence, the application's user interface), all the Mandelbrot fractal computation is done in a separate worker thread. The thread emits a signal when it is done rendering the fractal.

Similarly, the Blocking Fortune Client Example uses a separate thread for communicating with a TCP server asynchronously.

2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Slot on main thread not called when signal is emitted from another thread

I am trying to write a plugin for Wireshark, a Qt GUI application. Wireshark is mostly written in C with C++ and Qt used to handle the user interface. The plugin framework comprises mainly a set of three or four C callback functions. I'm writing the plugin in C++, exposing the callbacks using extern C declarations. The callbacks are being called correctly and that all looks fine.

The plugin needs to provide a TCP server but here I have simplified the code to demonstrate the problem I'm having. The code is:

syncro.h

syncro.cpp

mythread.h

mythread.cpp

packet-syncro.cpp

The function proto register syncro(void) is a Wireshark callback that gets called three times at startup.

When I run the code the extra thread starts OK and it starts to cycle around the loop with the 3 second sleep. However, the connected slot function Syncro::jumpToFrame(int new frame) does not get called. If I change the connect from QueuedConnection to DirectConnection the slot function gets called but, as expected, in the context of my serviceThread. I need the slot function to run on the main thread.

Unable to connect signal to a function inside main()

I am aware that to use the signals and slots mechanism of Qt inside a class, the class must include the Q OBJECT macro, but I am attempting to use signals and slots in main() , without using any class.

Here is my code so far:

Here is the GUI window generated:

From the above code, the exit button is connected to quit() , which is a Qt function, when clicked it works. The save button assigned to the function saveText() , is configured to exit, but does not do so.

Please tell me where I have gone wrong in understanding signals and slots in Qt.

Utiliser un thread travailleur avec Qt en employant les signaux et les slots

Qt fournit des classes de threads independantes de la plate-forme, une maniere thread-safe de poster des evenements et des connexions de signaux a slots entre les threads. La programmation multithreadee est un avantage des machines a plusieurs processeurs ; elle est aussi utile pour effectuer les operations chronophages sans geler l'interface utilisateur d'une application. Sans multithreading, les operations sont realisees sequentiellement, sans parallelisme possible.

Article lu fois.

Les deux auteur et traducteur

L'article

Publié le 5 fevrier 2012 - Mis à jour le 5 janvier 2019

Liens sociaux

I. L'article original▲

Cet article est une adaptation en langue francaise de Worker Thread in Qt using Signals Slots.

II. Connexions entre signaux et slots entre les threads▲

Qt fournit des classes de threads independantes de la plate-forme, une maniere thread-safe de poster des evenements et des connexions de signaux a slots entre les threads. La programmation multithreadee est un avantage des machines a plusieurs processeurs elle est aussi utile pour effectuer les operations chronophages sans geler l'interface utilisateur d'une application. Sans multithreading, les operations sont realisees sequentiellement, sans parallelisme possible.

Comme cela vient d'etre mentionne, Qt supporte les connexions de signaux a slots entre les threads. Cela fournit une maniere interessante de passer des donnees entre les threads.

Voici le prototype de la methode QObject::connect() :

Le dernier parametre est le type de connexion et il est important de le comprendre. La valeur par defaut est Qt::AutoConnection , ce qui signifie que, si le signal est emis d'un thread different de l'objet le recevant, le signal est mis dans la queue de gestion d'evenements (1), un comportement semblable a Qt::QueuedConnection . Sinon, le slot est invoque directement, comme Qt::DirectConnection . Le type de connexion est determine quand le signal est emis.

Dans le cas discute ici, on se montrera particulierement interesse par Qt::QueuedConnection , parce que :

  • il est thread-safe d'utiliser une telle connexion entre deux threads differents (au contraire de la connexion directe) ;
  • le slot est execute dans le thread de l'objet le recevant. Cela signifie que l'on peut emettre un signal du thread principal et le connecter a un slot dans un thread travailleur. Le traitement est alors effectue dans ce dernier.

III. Un exemple simple▲

On considere un exemple simple ou l on souhaite trier un vecteur d'entiers dans un thread separe. Par consequent, on devrait avoir deux threads : le principal pour l'interface et le thread travailleur qui s'occupe du tri.

Comme montre dans la figure ci-dessous, on doit avoir deux objets : un qui vit dans le thread principal ( Sorter ) et un dans le thread travailleur ( SorterWorker ).

On dit d'une instance de QObject qu'elle vit dans le thread dans lequel elle a ete creee. Les evenements pour cet objet sont geres par la boucle evenementielle du thread.

Pour la classe Sorter , puisqu'on veut creer un nouveau thread, on devra heriter de QThread (heritant elle-meme de QObject ). Elle fournira une methode sortAsync(QVector) qui sera appelee par les clients pour trier un vecteur de maniere asynchrone. Puisque l'operation est asynchrone, on doit aussi definir un signal vectorSorted(QVector) pour notifier le client de la fin du tri.

Voici quelques details sur l'implementation de cette classe.

Dans le constructeur, on demarre le thread travailleur (le code dans run() sera execute). Enfin, le constructeur attend que le thread soit pret (c'est-a-dire que l'objet SorterWorker ait ete cree et que les signaux et slots soient connectes) pour s'assurer que le client ne puisse effectuer de requete avant que le thread ne soit pret a les executer.

Dans la methode run() , on cree un objet SorterWorker . Il est important que cet objet soit cree dans la methode run() et non dans le constructeur de SorterWorker , de telle sorte qu'il vive dans le thread travailleur (et non dans le thread principal). On utilise un signal interne sortingRequested(QVector) pour rediriger les requetes de tri au SorterWorker dans le thread travailleur. Puisque le signal est emis dans le thread principal et que l'objet le recevant ( SorterWorker ) vit dans le thread travailleur, une connexion en queue va etre utilisee. Par consequent, le slot doSort(QVector) sera execute dans le thread travailleur.

On note aussi l'utilisation de QMetaType::qRegisterMetaType() avant de connecter les signaux et les slots. Quand un signal est mis dans la queue, les parametres doivent etre d'un type connu par le systeme de metaobjets de Qt, parce que Qt a besoin de copier les arguments pour les stocker dans un evenement en coulisses. En cas d'oubli, on aura l'erreur suivante :

IV. La classe SorterWorker▲

L'implementation de la classe SorterWorker est rapide. On doit juste s'assurer qu'elle herite de QObject (ne pas oublier la macro Q OBJECT pour que les signaux et slots soient utilisables). Les methodes telles que doSort(QVector) doivent etre definies comme des slots publics. Au cas ou ces methodes devraient retourner des donnees, on utilise des signaux. Ne pas oublier de faire passer les signaux aux clients dans la classe Sorter .

V. Utiliser le thread travailleur▲

Pour utiliser le thread travailleur, on doit simplement creer un objet Sorter et s'assurer de connecter son signal vectorSorted(QVector) a un slot local pour recuperer le resultat. On peut alors appeler la methode sortAsync(QVector) pour demander au thread travailleur de trier le vecteur.

VI. Debogage▲

Pour s'assurer que les fonctions sont executees dans le bon thread, on peut utiliser l'instruction suivante :

QThread::currentThreadId() est une fonction statique qui retourne l'identifiant du thread d'execution courant.

VII. L'alternative Qt Concurrent▲

Pour des cas simples, comme celui traite ici, Qt Concurrent est une bonne alternative qui necessitera moins de code.

On peut utiliser la fonction suivante pour lancer une fonction dans un thread separe :

Cela execute la fonction func dans un thread separe et retourne un objet QFuture. On peut verifier si la fonction a fini son travail en executant la methode QFuture::isFinished(). De maniere alternative, on peut utiliser un objet QFutureWatcher pour recevoir un signal a ce moment.

VIII. Remerciements▲

Merci a Guillaume Belz, Jacques Thery et escartefigue pour leur relecture attentive !

Vous avez aime ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants :

Copyright 2012 Christophe Dumez. Aucune reproduction, même partielle, ne peut être faite de ce site ni de l'ensemble de son contenu : textes, documents, images, etc. sans l'autorisation expresse de l'auteur. Sinon vous encourez selon la loi jusqu'à trois ans de prison et jusqu'à 300 000 € de dommages et intérêts.

  • Qt thread slots and signals

    Qt thread slots and signals Threads and QObjects QThread inherits QObject. It emits signals to indicate that the thread started or finished executing,...

  • Qt private slot vs public slot

    Does it make any difference, using public slots instead of private slots in Qt Does it make any difference, using public slots instead of private slots...

  • Raspberry pi 2 micro sd slot

    Micro-SD Slot defekt? Wie kann ich es Prufen Micro-SD Slot defekt? Wie kann ich es Prufen? Hi Mein raspby (B+ rev 2) hat einigerma?en funktioniert mit...

  • Raging bull casino bonus codesbirthday

    Raging Bull Casino Bonus Codesbirthday; The online mobile casino jackpots Raging Bull Casino Bonus Codesbirthday The online mobile casino jackpots Es...

  • What is agp slot function

    Agp Slot Definition And Function Expansion slots are used in motherboard so that you can install additional video cards, sound cards, and graphic cards...