source: trunk/doc/src/threads.qdoc@ 477

Last change on this file since 477 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 26.5 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the documentation of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42/*!
43 \page threads.html
44 \title Thread Support in Qt
45 \ingroup architecture
46 \brief A detailed discussion of thread handling in Qt.
47
48 Qt provides thread support in the form of platform-independent
49 threading classes, a thread-safe way of posting events, and
50 signal-slot connections across threads. This makes it easy to
51 develop portable multithreaded Qt applications and take advantage
52 of multiprocessor machines. Multithreaded programming is also a
53 useful paradigm for performing time-consuming operations without
54 freezing the user interface of an application.
55
56 Earlier versions of Qt offered an option to build the library
57 without thread support. Since Qt 4.0, threads are always enabled.
58
59 This document is intended for an audience that has knowledge of,
60 and experience with, multithreaded applications. If you are new
61 to threading see our \l{#reading}{Recommended Reading} list.
62
63 Topics:
64
65 \tableofcontents
66
67 \section1 The Threading Classes
68
69 Qt includes the following thread classes:
70
71 \list
72 \o QThread provides the means to start a new thread.
73 \o QThreadStorage provides per-thread data storage.
74 \o QThreadPool manages a pool of threads that run QRunnable objects.
75 \o QRunnable is an abstract class representing a runnable object.
76 \o QMutex provides a mutual exclusion lock, or mutex.
77 \o QMutexLocker is a convenience class that automatically locks
78 and unlocks a QMutex.
79 \o QReadWriteLock provides a lock that allows simultaneous read access.
80 \o QReadLocker and QWriteLocker are convenience classes that automatically
81 lock and unlock a QReadWriteLock.
82 \o QSemaphore provides an integer semaphore (a generalization of a mutex).
83 \o QWaitCondition provides a way for threads to go to sleep until
84 woken up by another thread.
85 \o QAtomicInt provides atomic operations on integers.
86 \o QAtomicPointer provides atomic operations on pointers.
87 \endlist
88
89 \note Qt's threading classes are implemented with native threading APIs;
90 e.g., Win32 and pthreads. Therefore, they can be used with threads of the
91 same native API.
92
93 \section2 Creating a Thread
94
95 To create a thread, subclass QThread and reimplement its
96 \l{QThread::run()}{run()} function. For example:
97
98 \snippet doc/src/snippets/threads/threads.h 0
99 \codeline
100 \snippet doc/src/snippets/threads/threads.cpp 0
101 \snippet doc/src/snippets/threads/threads.cpp 1
102 \dots
103 \snippet doc/src/snippets/threads/threads.cpp 2
104
105 Then, create an instance of the thread object and call
106 QThread::start(). The code that appears in the
107 \l{QThread::run()}{run()} reimplementation will then be executed
108 in a separate thread. Creating threads is explained in more
109 detail in the QThread documentation.
110
111 Note that QCoreApplication::exec() must always be called from the
112 main thread (the thread that executes \c{main()}), not from a
113 QThread. In GUI applications, the main thread is also called the
114 GUI thread because it's the only thread that is allowed to
115 perform GUI-related operations.
116
117 In addition, you must create the QApplication (or
118 QCoreApplication) object before you can create a QThread.
119
120 \section2 Synchronizing Threads
121
122 The QMutex, QReadWriteLock, QSemaphore, and QWaitCondition
123 classes provide means to synchronize threads. While the main idea
124 with threads is that they should be as concurrent as possible,
125 there are points where threads must stop and wait for other
126 threads. For example, if two threads try to access the same
127 global variable simultaneously, the results are usually
128 undefined.
129
130 QMutex provides a mutually exclusive lock, or mutex. At most one
131 thread can hold the mutex at any time. If a thread tries to
132 acquire the mutex while the mutex is already locked, the thread will
133 be put to sleep until the thread that currently holds the mutex
134 unlocks it. Mutexes are often used to protect accesses to shared
135 data (i.e., data that can be accessed from multiple threads
136 simultaneously). In the \l{Reentrancy and Thread-Safety} section
137 below, we will use it to make a class thread-safe.
138
139 QReadWriteLock is similar to QMutex, except that it distinguishes
140 between "read" and "write" access to shared data and allows
141 multiple readers to access the data simultaneously. Using
142 QReadWriteLock instead of QMutex when it is possible can make
143 multithreaded programs more concurrent.
144
145 QSemaphore is a generalization of QMutex that protects a certain
146 number of identical resources. In contrast, a mutex protects
147 exactly one resource. The \l{threads/semaphores}{Semaphores}
148 example shows a typical application of semaphores: synchronizing
149 access to a circular buffer between a producer and a consumer.
150
151 QWaitCondition allows a thread to wake up other threads when some
152 condition has been met. One or many threads can block waiting for
153 a QWaitCondition to set a condition with
154 \l{QWaitCondition::wakeOne()}{wakeOne()} or
155 \l{QWaitCondition::wakeAll()}{wakeAll()}. Use
156 \l{QWaitCondition::wakeOne()}{wakeOne()} to wake one randomly
157 selected event or \l{QWaitCondition::wakeAll()}{wakeAll()} to
158 wake them all. The \l{threads/waitconditions}{Wait Conditions}
159 example shows how to solve the producer-consumer problem using
160 QWaitCondition instead of QSemaphore.
161
162 Note that Qt's synchronization classes rely on the use of properly
163 aligned pointers. For instance, you cannot use packed classes with
164 MSVC.
165
166 \target qtconcurrent intro
167 \section1 QtConcurrent
168
169 The QtConcurrent namespace provides high-level APIs that make it
170 possible to write multi-threaded programs without using low-level
171 threading primitives such as mutexes, read-write locks, wait
172 conditions, or semaphores. Programs written with QtConcurrent
173 automatically adjust the number of threads used according to the
174 number of processor cores available. This means that applications
175 written today will continue to scale when deployed on multi-core
176 systems in the future.
177
178 QtConcurrent includes functional programming style APIs for
179 parallel list processing, including a MapReduce and FilterReduce
180 implementation for shared-memory (non-distributed) systems, and
181 classes for managing asynchronous computations in GUI
182 applications:
183
184 \list
185
186 \o QtConcurrent::map() applies a function to every item in a container,
187 modifying the items in-place.
188
189 \o QtConcurrent::mapped() is like map(), except that it returns a new
190 container with the modifications.
191
192 \o QtConcurrent::mappedReduced() is like mapped(), except that the
193 modified results are reduced or folded into a single result.
194
195 \o QtConcurrent::filter() removes all items from a container based on the
196 result of a filter function.
197
198 \o QtConcurrent::filtered() is like filter(), except that it returns a new
199 container with the filtered results.
200
201 \o QtConcurrent::filteredReduced() is like filtered(), except that the
202 filtered results are reduced or folded into a single result.
203
204 \o QtConcurrent::run() runs a function in another thread.
205
206 \o QFuture represents the result of an asynchronous computation.
207
208 \o QFutureIterator allows iterating through results available via QFuture.
209
210 \o QFutureWatcher allows monitoring a QFuture using signals-and-slots.
211
212 \o QFutureSynchronizer is a convenience class that automatically
213 synchronizes several QFutures.
214
215 \endlist
216
217 Qt Concurrent supports several STL-compatible container and iterator types,
218 but works best with Qt containers that have random-access iterators, such as
219 QList or QVector. The map and filter functions accept both containers and begin/end iterators.
220
221 STL Iterator support overview:
222
223 \table
224 \header
225 \o Iterator Type
226 \o Example classes
227 \o Support status
228 \row
229 \o Input Iterator
230 \o
231 \o Not Supported
232 \row
233 \o Output Iterator
234 \o
235 \o Not Supported
236 \row
237 \o Forward Iterator
238 \o std::slist
239 \o Supported
240 \row
241 \o Bidirectional Iterator
242 \o QLinkedList, std::list
243 \o Supported
244 \row
245 \o Random Access Iterator
246 \o QList, QVector, std::vector
247 \o Supported and Recommended
248 \endtable
249
250 Random access iterators can be faster in cases where Qt Concurrent is iterating
251 over a large number of lightweight items, since they allow skipping to any point
252 in the container. In addition, using random access iterators allows Qt Concurrent
253 to provide progress information trough QFuture::progressValue() and QFutureWatcher::
254 progressValueChanged().
255
256 The non in-place modifying functions such as mapped() and filtered() makes a
257 copy of the container when called. If you are using STL containers this copy operation
258 might take some time, in this case we recommend specifying the begin and end iterators
259 for the container instead.
260
261 \keyword reentrant
262 \keyword thread-safe
263 \section1 Reentrancy and Thread-Safety
264
265 Throughout the Qt documentation, the terms \e reentrant and \e
266 thread-safe are used to specify how a function can be used in
267 multithreaded applications:
268
269 \list
270 \o A \e reentrant function can be called simultaneously by
271 multiple threads provided that each invocation of the function
272 references unique data.
273 \o A \e thread-safe function can be called simultaneously by
274 multiple threads when each invocation references shared data.
275 All access to the shared data is serialized.
276 \endlist
277
278 By extension, a class is said to be reentrant if each and every
279 one of its functions can be called simultaneously by multiple
280 threads on different instances of the class. Similarly, the class
281 is said to be thread-safe if the functions can be called by
282 different threads on the same instance.
283
284 Classes in the documentation will be documented as thread-safe only
285 if they are intended to be used by multiple threads.
286
287 Note that the terminology in this domain isn't entirely
288 standardized. POSIX uses a somewhat different definition of
289 reentrancy and thread-safety for its C APIs. When dealing with an
290 object-oriented C++ class library such as Qt, the definitions
291 must be adapted.
292
293 Most C++ classes are inherently reentrant, since they typically
294 only reference member data. Any thread can call such a member
295 function on an instance of the class, as long as no other thread
296 is calling a member function on the same instance. For example,
297 the \c Counter class below is reentrant:
298
299 \snippet doc/src/snippets/threads/threads.cpp 3
300 \snippet doc/src/snippets/threads/threads.cpp 4
301
302 The class isn't thread-safe, because if multiple threads try to
303 modify the data member \c n, the result is undefined. This is
304 because C++'s \c ++ and \c -- operators aren't necessarily
305 atomic. Indeed, they usually expand to three machine
306 instructions:
307
308 \list 1
309 \o Load the variable's value in a register.
310 \o Increment or decrement the register's value.
311 \o Store the register's value back into main memory.
312 \endlist
313
314 If thread A and thread B load the variable's old value
315 simultaneously, increment their register, and store it back, they
316 end up overwriting each other, and the variable is incremented
317 only once!
318
319 Clearly, the access must be serialized: Thread A must perform
320 steps 1, 2, 3 without interruption (atomically) before thread B
321 can perform the same steps; or vice versa. An easy way to make
322 the class thread-safe is to protect all access to the data
323 members with a QMutex:
324
325 \snippet doc/src/snippets/threads/threads.cpp 5
326 \snippet doc/src/snippets/threads/threads.cpp 6
327
328 The QMutexLocker class automatically locks the mutex in its
329 constructor and unlocks it when the destructor is invoked, at the
330 end of the function. Locking the mutex ensures that access from
331 different threads will be serialized. The \c mutex data member is
332 declared with the \c mutable qualifier because we need to lock
333 and unlock the mutex in \c value(), which is a const function.
334
335 Most Qt classes are reentrant and not thread-safe, to avoid the
336 overhead of repeatedly locking and unlocking a QMutex. For
337 example, QString is reentrant, meaning that you can use it in
338 different threads, but you can't access the same QString object
339 from different threads simultaneously (unless you protect it with
340 a mutex yourself). A few classes and functions are thread-safe;
341 these are mainly thread-related classes such as QMutex, or
342 fundamental functions such as QCoreApplication::postEvent().
343
344 \section1 Threads and QObjects
345
346 QThread inherits QObject. It emits signals to indicate that the
347 thread started or finished executing, and provides a few slots as
348 well.
349
350 More interesting is that \l{QObject}s can be used in multiple
351 threads, emit signals that invoke slots in other threads, and
352 post events to objects that "live" in other threads. This is
353 possible because each thread is allowed to have its own event
354 loop.
355
356 \section2 QObject Reentrancy
357
358 QObject is reentrant. Most of its non-GUI subclasses, such as
359 QTimer, QTcpSocket, QUdpSocket, QHttp, QFtp, and QProcess, are
360 also reentrant, making it possible to use these classes from
361 multiple threads simultaneously. Note that these classes are
362 designed to be created and used from within a single thread;
363 creating an object in one thread and calling its functions from
364 another thread is not guaranteed to work. There are three
365 constraints to be aware of:
366
367 \list
368 \o \e{The child of a QObject must always be created in the thread
369 where the parent was created.} This implies, among other
370 things, that you should never pass the QThread object (\c
371 this) as the parent of an object created in the thread (since
372 the QThread object itself was created in another thread).
373
374 \o \e{Event driven objects may only be used in a single thread.}
375 Specifically, this applies to the \l{timers.html}{timer
376 mechanism} and the \l{QtNetwork}{network module}. For example,
377 you cannot start a timer or connect a socket in a thread that
378 is not the \l{QObject::thread()}{object's thread}.
379
380 \o \e{You must ensure that all objects created in a thread are
381 deleted before you delete the QThread.} This can be done
382 easily by creating the objects on the stack in your
383 \l{QThread::run()}{run()} implementation.
384 \endlist
385
386 Although QObject is reentrant, the GUI classes, notably QWidget
387 and all its subclasses, are not reentrant. They can only be used
388 from the main thread. As noted earlier, QCoreApplication::exec()
389 must also be called from that thread.
390
391 In practice, the impossibility of using GUI classes in other
392 threads than the main thread can easily be worked around by
393 putting time-consuming operations in a separate worker thread and
394 displaying the results on screen in the main thread when the
395 worker thread is finished. This is the approach used for
396 implementing the \l{threads/mandelbrot}{Mandelbrot} and
397 the \l{network/blockingfortuneclient}{Blocking Fortune Client}
398 example.
399
400 \section2 Per-Thread Event Loop
401
402 Each thread can have its own event loop. The initial thread
403 starts its event loops using QCoreApplication::exec(); other
404 threads can start an event loop using QThread::exec(). Like
405 QCoreApplication, QThread provides an
406 \l{QThread::exit()}{exit(int)} function and a
407 \l{QThread::quit()}{quit()} slot.
408
409 An event loop in a thread makes it possible for the thread to use
410 certain non-GUI Qt classes that require the presence of an event
411 loop (such as QTimer, QTcpSocket, and QProcess). It also makes it
412 possible to connect signals from any threads to slots of a
413 specific thread. This is explained in more detail in the
414 \l{Signals and Slots Across Threads} section below.
415
416 \image threadsandobjects.png Threads, objects, and event loops
417
418 A QObject instance is said to \e live in the thread in which it
419 is created. Events to that object are dispatched by that thread's
420 event loop. The thread in which a QObject lives is available using
421 QObject::thread().
422
423 Note that for QObjects that are created before QApplication,
424 QObject::thread() returns zero. This means that the main thread
425 will only handle posted events for these objects; other event
426 processing is not done at all for objects with no thread. Use the
427 QObject::moveToThread() function to change the thread affinity for
428 an object and its children (the object cannot be moved if it has a
429 parent).
430
431 Calling \c delete on a QObject from another thread than the
432 thread where it is created (or accessing the object in other
433 ways) is unsafe unless you can guarantee that the object isn't
434 processing events at the same moment. Use QObject::deleteLater()
435 instead; it will post a
436 \l{QEvent::DeferredDelete}{DeferredDelete} event, which the
437 event loop of the object's thread will eventually pick up.
438
439 If no event loop is running, events won't be delivered to the
440 object. For example, if you create a QTimer object in a thread
441 but never call \l{QThread::exec()}{exec()}, the QTimer will never emit its
442 \l{QTimer::timeout()}{timeout()} signal. Calling
443 \l{QObject::deleteLater()}{deleteLater()} won't work either. (These
444 restrictions apply to the main thread as well.)
445
446 You can manually post events to any object in any thread at any
447 time using the thread-safe function
448 QCoreApplication::postEvent(). The events will automatically be
449 dispatched by the event loop of the thread where the object was
450 created.
451
452 Event filters are supported in all threads, with the restriction
453 that the monitoring object must live in the same thread as the
454 monitored object. Similarly, QCoreApplication::sendEvent()
455 (unlike \l{QCoreApplication::postEvent()}{postEvent()}) can only
456 be used to dispatch events to objects living in the thread from
457 which the function is called.
458
459 \section2 Accessing QObject Subclasses from Other Threads
460
461 QObject and all of its subclasses are not thread-safe. This
462 includes the entire event delivery system. It is important to keep
463 in mind that the event loop may be delivering events to your
464 QObject subclass while you are accessing the object from another