Chapter 20. Multithreading

So far, whatever we did in our Qt programs, only one thing happened at a time. Of course, we could run several instances of a program, but that was a different issue; the two processes were completely independent of each other. In this chapter, we will look at multithreading, which lets you have several threads of control in one process at the same time. Of course, unless you have a multiprocessor machine, only one of these threads can be executed at a time. To the observer (and that includes you, the developer), however, it looks like all (or at least some) threads are run at the same time.

Since threads run in the same process, all threads have access to the process’s memory, including all variables. This situation brings an inherent danger: one thread might make a change to a variable and before it can use that change, another thread could overwrite it again. This scenario might bring unexpected results for the first thread. The only data that is safe is data that is on the stack because each thread has a stack of its own. Thus, local variables cannot be shared between two threads, and each thread is free to access its own local variable at its leisure without needing to pay attention to what other threads do.

Multithreading looks deceptively simple, but these synchronization problems make it an extremely difficult task. Sure, there are tools and techniques for solving these problems, but it is still very difficult, and synchronization problems are ...

Get Programming with Qt, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.