17.2.1.  Thread Safety and QObjects

[ fromfile: threads.xml id: threadsafety ]

A reentrant method is one that can be called simultaneously by multiple threads, provided no two invocations of the method attempt to reference the same data. A thread-safe method can be called simultaneously by multiple threads at any time, because any shared data is protected somehow (e.g., by QMutex) from simultaneous access. A class is reentrant or thread-safe if all of its non-static functions are reentrant or thread-safe.

A QObject that was created in a particular thread "belongs to", or has an affinity to, that thread. Its children must also belong to the same thread. Having parent-child relationships that cross over threads is forbidden by Qt.

A thread-safe object is one that can be accessed concurrently by multiple threads and is guaranteed to always be in a "valid" state. QObjects are not "thread safe" by default. To make an object thread safe there are a number of approaches to take. Some are listed here, but we recommend the Qt Thread Support documentation for further details.

  1. QMutex, for mutual exclusion, along with QMutexLocker, enables an individual thread T to protect (lock) an object or a section of code so that no other thread can access it until T releases (unlocks) it.

  2. QWaitCondition, combined with QMutex, can be used to put a thread into a non-busy block state where it can wait for another thread to wake it up.

  3. A QSemaphore is a more generalized QMutex for situations where a thread may need to lock more than one resource before doing its work. Semaphores make it possible to ensure that a thread locks resources only when enough are available for it to do its job.

There are more examples demonstrating how to use QtConcurrent in the Qt examples: $QTDIR/examples/qtconcurrent.