Qt Invoke Slot Another Thread

Welcome to Qt Centre. Calling a slot from another thread. So far to send a command I just can just create a signal in the GUI class, like 'doCall' which gets hooked up to the 'call' slot in the Skype thread. Due to the magic of queued connections, this works just fine.

Home > Articles > Programming > C/C++

  1. Creating Threads
Page 1 of 4Next >
This chapter shows how to subclass QThread and how to synchronize threads. It also shows how to communicate with the main thread from secondary threads while the event loop is running.
This chapter is from the book
C++ GUI Programming with Qt4, 2nd Edition

This chapter is from the book

This chapter is from the book

14. Multithreading

  • Creating Threads
  • Synchronizing Threads
  • Communicating with the Main Thread
  • Using Qt's Classes in Secondary Threads

Conventional GUI applications have one thread of execution and perform one operation at a time. If the user invokes a time-consuming operation from the user interface, the interface typically freezes while the operation is in progress. Chapter 7 presents some solutions to this problem. Multithreading is another solution.

In a multithreaded application, the GUI runs in its own thread and additional processing takes place in one or more other threads. This results in applications that have responsive GUIs even during intensive processing. When runnning on a single processor, multithreaded applications may run slower than a single-threaded equivalent due to the overhead of having multiple threads. But on multiprocessor systems, which are becoming increasingly common, multithreaded applications can execute several threads simultaneously on different processors, resulting in better overall performance.

In this chapter, we will start by showing how to subclass QThread and how to use QMutex, QSemaphore, and QWaitCondition to synchronize threads. [*] Then we will see how to communicate with the main thread from secondary threads while the event loop is running. Finally, we round off with a review of which Qt classes can be used in secondary threads and which cannot.

Multithreading is a large topic with many books devoted to the subject—for example, Threads Primer: A Guide to Multithreaded Programming by Bil Lewis and Daniel J. Berg (Prentice Hall, 1995) and Multithreaded, Parallel, and Distributed Programming by Gregory Andrews (Addison-Wesley, 2000). Here it is assumed that you already understand the fundamentals of multithreaded programming, so the focus is on explaining how to develop multithreaded Qt applications rather than on the subject of threading itself.

Creating Threads

Providing multiple threads in a Qt application is straightforward: We just subclass QThread and reimplement its run() function. To show how this works, we will start by reviewing the code for a very simple QThread subclass that repeatedly prints a given string on a console. The application's user interface is shown in Figure 14.1.

Figure 14.1 The Threads application

The Thread class is derived from QThread and reimplements the run() function. It provides two additional functions: setMessage() and stop().

The stopped variable is declared volatile because it is accessed from different threads and we want to be sure that it is freshly read every time it is needed. If we omitted the volatile keyword, the compiler might optimize access to the variable, possibly leading to incorrect results.

We set stopped to false in the constructor.

The run() function is called to start executing the thread. As long as the stopped variable is false, the function keeps printing the given message to the console. The thread terminates when control leaves the run() function.

Qt call slot from different thread

The stop() function sets the stopped variable to true, thereby telling run() to stop printing text to the console. This function can be called from any thread at any time. For the purposes of this example, we assume that assignment to a bool is an atomic operation. This is a reasonable assumption, considering that a bool can have only two states. We will see later in this section how to use QMutex to guarantee that assigning to a variable is an atomic operation.

QThread provides a terminate() function that terminates the execution of a thread while it is still running. Using terminate() is not recommended, since it can stop the thread at any point and does not give the thread any chance to clean up after itself. It is always safer to use a stopped variable and a stop() function as we did here.

We will now see how to use the Thread class in a small Qt application that uses two threads, A and B, in addition to the main thread.

The ThreadDialog class declares two variables of type Thread and some buttons to provide a basic user interface.

In the constructor, we call setMessage() to make the first thread repeatedly print 'A's and the second thread 'B's.

When the user clicks the button for thread A, startOrStopThreadA() stops the thread if it was running and starts it otherwise. It also updates the button's text.

The code for startOrStopThreadB() is structurally identical.

If the user clicks Quit or closes the window, we stop any running threads and wait for them to finish (using QThread::wait()) before we call QCloseEvent::accept(). This ensures that the application exits in a clean state, although it doesn't really matter in this example.

If you run the application and click Start A, the console will be filled with 'A's. If you click Start B, it will now fill with alternating sequences of 'A's and 'B's. Click Stop A, and now it will print only 'B's.

Related Resources

  • Book $31.99
  • Book $35.99
  • Book $43.99

Home > Articles > Programming > C/C++

  1. Communicating with the Main Thread
< BackPage 3 of 4Next >
This chapter is from the book
C++ GUI Programming with Qt4, 2nd Edition

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.

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 Invoke Slot Another 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.

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.

Qt Invoke Slot

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.

Related Resources

  • Book $31.99

Qt Call Slot From Another Thread

  • Book $35.99

Qt Call Slot From Different Thread

  • Book $43.99