Thread safety in Qt p.28 A function is: Thread safe: if it's safe for it to be invoked at the same time, from multiple threads, on the same data, without synchronization Reentrant: if it's safe for it to be invoked at the same time, from multiple threads, on different data; otherwise it requires external synchronization. Qt supports these signal-slot connection types: Auto Connection(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.' Direct ConnectionThe slot is invoked immediately, when the signal is emitted.
This example was ported from the PyQt4 version by Guðjón Guðjónsson.
Introduction
In some applications it is often necessary to perform long-running tasks, such as computations or network operations, that cannot be broken up into smaller pieces and processed alongside normal application events. In such cases, we would like to be able to perform these tasks in a way that does not interfere with the normal running of the application, and ensure that the user interface continues to be updated. One way of achieving this is to perform these tasks in a separate thread to the main user interface thread, and only interact with it when we have results we need to display.
This example shows how to create a separate thread to perform a task - in this case, drawing stars for a picture - while continuing to run the main user interface thread. The worker thread draws each star onto its own individual image, and it passes each image back to the example's window which resides in the main application thread.
The User Interface
We begin by importing the modules we require. We need the math and random modules to help us draw stars.
The main window in this example is just a QWidget. We create a single Worker instance that we can reuse as required.
The user interface consists of a label, spin box and a push button that the user interacts with to configure the number of stars that the thread wil draw. The output from the thread is presented in a QLabel instance, viewer.
We connect the standard finished() and terminated() signals from the thread to the same slot in the widget. This will reset the user interface when the thread stops running. The custom output(QRect, QImage) signal is connected to the addImage() slot so that we can update the viewer label every time a new star is drawn.
The start button's clicked() signal is connected to the makePicture() slot, which is responsible for starting the worker thread.
We place each of the widgets into a grid layout and set the window's title:
The makePicture() slot needs to do three things: disable the user interface widgets that are used to start a thread, clear the viewer label with a new pixmap, and start the thread with the appropriate parameters.
Since the start button is the only widget that can cause this slot to be invoked, we simply disable it before starting the thread, avoiding problems with re-entrancy.
We call a custom method in the Worker thread instance with the size of the viewer label and the number of stars, obtained from the spin box.
Whenever is star is drawn by the worker thread, it will emit a signal that is connected to the addImage() slot. This slot is called with a QRect value, indicating where the star should be placed in the pixmap held by the viewer label, and an image of the star itself:
The statistic shows the monthly revenue from online casinos in New Jersey from January 2019 to September 2020, by operator. Try our corporate solution for free! New Jersey Online Gambling Revenue Every month the Division of Gaming Enforcement in New Jersey releases the previous month's legal online gambling revenue for each company. There are a number of New Jersey casinos that operate multiple online brands, we list each site next to their parent company. Figures released Tuesday by the New Jersey Division of Gaming Enforcement show the state's licensed online gambling operators generated combined revenue of $49.3m in December, a 70% improvement.
We use a QPainter to draw the image at the appropriate place on the label's pixmap.
The updateUi() slot is called when a thread stops running. Since we usually want to let the user run the thread again, we reset the user interface to enable the start button to be pressed:
Now that we have seen how an instance of the Window class uses the worker thread, let us take a look at the thread's implementation.
The Worker Thread
The worker thread is implemented as a PyQt thread rather than a Python thread since we want to take advantage of the signals and slots mechanism to communicate with the main application.
We define size and stars attributes that store information about the work the thread is required to do, and we assign default values to them. The exiting attribute is used to tell the thread to stop processing.
Each star is drawn using a QPainterPath that we define in advance:
Before a Worker object is destroyed, we need to ensure that it stops processing. For this reason, we implement the following method in a way that indicates to the part of the object that performs the processing that it must stop, and waits until it does so.
For convenience, we define a method to set up the attributes required by the thread before starting it.
The start() method is a special method that sets up the thread and calls our implementation of the run() method. We provide the render() method instead of letting our own run() method take extra arguments because the run() method is called by PyQt itself with no arguments.
The run() method is where we perform the processing that occurs in the thread provided by the Worker instance:
Information stored as attributes in the instance determines the number of stars to be drawn and the area over which they will be distributed.
We draw the number of stars requested as long as the exiting attribute remains False. This additional check allows us to terminate the thread on demand by setting the exiting attribute to True at any time.
The drawing code is not particularly relevant to this example. We simply draw on an appropriately-sized transparent image.
For each star drawn, we send the main thread information about where it should be placed along with the star's image by emitting our custom output() signal:
Since QRect and QImage objects can be serialized for transmission via the signals and slots mechanism, they can be sent between threads in this way, making it convenient to use threads in a wide range of situations where built-in types are used.
Running the Example
We only need one more piece of code to complete the example:
Home > Articles > Programming > C/C++
␡- Communicating with the Main Thread
This chapter is from the book
This chapter is from the book
Communicating with the Main Thread
When a Qt application starts, only one thread is running—the main thread. This is the only thread that is allowed to create the QApplication or QCoreApplication object and call exec() on it. After the call to exec(), this thread is either waiting for an event or processing an event.
The main thread can start new threads by creating objects of a QThread subclass, as we did in the previous section. If these new threads need to communicate among themselves, they can use shared variables together with mutexes, read-write locks, semaphores, or wait conditions. But none of these techniques can be used to communicate with the main thread, since they would lock the event loop and freeze the user interface.
The solution for communicating from a secondary thread to the main thread is to use signal–slot connections across threads. Normally, the signals and slots mechanism operates synchronously, meaning that the slots connected to a signal are invoked immediately when the signal is emitted, using a direct function call.
However, when we connect objects that 'live' in different threads, the mechanism becomes asynchronous. (This behavior can be changed through an optional fifth parameter to QObject::connect().) Behind the scenes, these connections are implemented by posting an event. The slot is then called by the event loop of the thread in which the receiver object exists. By default, a QObject exists in the thread in which it was created; this can be changed at any time by calling QObject::moveToThread().
To illustrate how signal–slot connections across threads work, we will review the code of the Image Pro application, a basic image processing application that allows the user to rotate, resize, and change the color depth of an image. The application (shown in Figure 14.3), uses one secondary thread to perform operations on images without locking the event loop. This makes a significant difference when processing very large images. The secondary thread has a list of tasks, or 'transactions', to accomplish and sends events to the main window to report progress.
We use a QPainter to draw the image at the appropriate place on the label's pixmap.
The updateUi() slot is called when a thread stops running. Since we usually want to let the user run the thread again, we reset the user interface to enable the start button to be pressed:
Now that we have seen how an instance of the Window class uses the worker thread, let us take a look at the thread's implementation.
The Worker Thread
The worker thread is implemented as a PyQt thread rather than a Python thread since we want to take advantage of the signals and slots mechanism to communicate with the main application.
We define size and stars attributes that store information about the work the thread is required to do, and we assign default values to them. The exiting attribute is used to tell the thread to stop processing.
Each star is drawn using a QPainterPath that we define in advance:
Before a Worker object is destroyed, we need to ensure that it stops processing. For this reason, we implement the following method in a way that indicates to the part of the object that performs the processing that it must stop, and waits until it does so.
For convenience, we define a method to set up the attributes required by the thread before starting it.
The start() method is a special method that sets up the thread and calls our implementation of the run() method. We provide the render() method instead of letting our own run() method take extra arguments because the run() method is called by PyQt itself with no arguments.
The run() method is where we perform the processing that occurs in the thread provided by the Worker instance:
Information stored as attributes in the instance determines the number of stars to be drawn and the area over which they will be distributed.
We draw the number of stars requested as long as the exiting attribute remains False. This additional check allows us to terminate the thread on demand by setting the exiting attribute to True at any time.
The drawing code is not particularly relevant to this example. We simply draw on an appropriately-sized transparent image.
For each star drawn, we send the main thread information about where it should be placed along with the star's image by emitting our custom output() signal:
Since QRect and QImage objects can be serialized for transmission via the signals and slots mechanism, they can be sent between threads in this way, making it convenient to use threads in a wide range of situations where built-in types are used.
Running the Example
We only need one more piece of code to complete the example:
Home > Articles > Programming > C/C++
␡- Communicating with the Main Thread
This chapter is from the book
This chapter is from the book
Communicating with the Main Thread
When a Qt application starts, only one thread is running—the main thread. This is the only thread that is allowed to create the QApplication or QCoreApplication object and call exec() on it. After the call to exec(), this thread is either waiting for an event or processing an event.
The main thread can start new threads by creating objects of a QThread subclass, as we did in the previous section. If these new threads need to communicate among themselves, they can use shared variables together with mutexes, read-write locks, semaphores, or wait conditions. But none of these techniques can be used to communicate with the main thread, since they would lock the event loop and freeze the user interface.
The solution for communicating from a secondary thread to the main thread is to use signal–slot connections across threads. Normally, the signals and slots mechanism operates synchronously, meaning that the slots connected to a signal are invoked immediately when the signal is emitted, using a direct function call.
However, when we connect objects that 'live' in different threads, the mechanism becomes asynchronous. (This behavior can be changed through an optional fifth parameter to QObject::connect().) Behind the scenes, these connections are implemented by posting an event. The slot is then called by the event loop of the thread in which the receiver object exists. By default, a QObject exists in the thread in which it was created; this can be changed at any time by calling QObject::moveToThread().
To illustrate how signal–slot connections across threads work, we will review the code of the Image Pro application, a basic image processing application that allows the user to rotate, resize, and change the color depth of an image. The application (shown in Figure 14.3), uses one secondary thread to perform operations on images without locking the event loop. This makes a significant difference when processing very large images. The secondary thread has a list of tasks, or 'transactions', to accomplish and sends events to the main window to report progress.
Figure 14.3 The Image Pro application
The interesting part of the ImageWindow constructor is the two signal–slot connections. Both of them involve signals emitted by the TransactionThread object, which we will cover in a moment.
The flipHorizontally() slot creates a 'flip' transaction and registers it using the private function addTransaction(). The flipVertically(), resizeImage(), convertTo32Bit(), convertTo8Bit(), and convertTo1Bit() functions are similar.
The addTransaction() function adds a transaction to the secondary thread's transaction queue and disables the Open, Save, and Save As actions while transactions are being processed.
The allTransactionsDone() slot is called when the TransactionThread's transaction queue becomes empty.
Now, let's turn to the TransactionThread class. Like most QThread subclasses, it is somewhat tricky to implement, because the run() function executes in its own thread, whereas the other functions (including the constructor and the destructor) are called from the main thread. The class definition follows:
The TransactionThread class maintains a queue of transactions to process and executes them one after the other in the background. In the private section, we declare four member variables:
- currentImage holds the image onto which the transactions are applied.
- transactions is the queue of pending transactions.
- transactionAdded is a wait condition that is used to wake up the thread when a new transaction has been added to the queue.
- mutex is used to protect the currentImage and transactions member variables against concurrent access.
Here is the class's constructor:
In the constructor, we simply call QThread::start() to launch the thread that will execute the transactions.
In the destructor, we empty the transaction queue and add a special EndTransaction marker to the queue. Then we wake up the thread and wait for it to finish using QThread::wait(), before the base class's destructor is implicitly invoked. Failing to call wait() would most probably result in a crash when the thread tries to access the class's member variables.
The QMutexLocker's destructor unlocks the mutex at the end of the inner block, just before the wait() call. It is important to unlock the mutex before calling wait(); otherwise, the program could end up in a deadlock situation, where the secondary thread waits forever for the mutex to be unlocked, and the main thread holds the mutex and waits for the secondary thread to finish before proceeding.
The addTransaction() function adds a transaction to the transaction queue and wakes up the transaction thread if it isn't already running. All accesses to the transactions member variable are protected by a mutex, because the main thread might modify them through addTransaction() at the same time as the secondary thread is iterating over transactions.
Qt Call Slot Thread Tool
The setImage() and image() functions allow the main thread to set the image on which the transactions should be performed, and to retrieve the resulting image once all the transactions are done.
The run() function goes through the transaction queue and executes each transaction in turn by calling apply() on them, until it reaches the EndTransaction marker. If the transaction queue is empty, the thread waits on the 'transaction added' condition.
Qt Call Slot In Different Thread
Just before we execute a transaction, we emit the transactionStarted() signal with a message to display in the application's status bar. When all the transactions have finished processing, we emit the allTransactionsDone() signal.
Qt Call Slot From Another Thread
The Transaction class is an abstract base class for operations that the user can perform on an image. The virtual destructor is necessary because we need to delete instances of Transaction subclasses through a Transaction pointer. Transaction has three concrete subclasses: FlipTransaction, ResizeTransaction, and ConvertDepthTransaction. We will only review FlipTransaction; the other two classes are similar.
The FlipTransaction constructor takes one parameter that specifies the orientation of the flip (horizontal or vertical).
The apply() function calls QImage::mirrored() on the QImage it receives as a parameter and returns the resulting QImage.
The message() function returns the message to display in the status bar while the operation is in progress. This function is called in TransactionThread::run() when emitting the transactionStarted() signal.
The Image Pro application shows how Qt's signals and slots mechanism makes it easy to communicate with the main thread from a secondary thread. Implementing the secondary thread is trickier, because we must protect our member variables using a mutex, and we must put the thread to sleep and wake it up appropriately using a wait condition. The two-part Qt Quarterly article series 'Monitors and Wait Conditions in Qt', available online at http://doc.trolltech.com/qq/qq21-monitors.html and http://doc.trolltech.com/qq/qq22-monitors2.html, presents some more ideas on how to develop and test QThread subclasses that use mutexes and wait conditions for synchronization.
Qt Call Slot Thread Gages
Related Resources
- Book $31.99
- eBook (Watermarked) $25.59
Qt Call Slot Thread Holders
- eBook (Watermarked) $28.79