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

Last change on this file since 321 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
465 thread.
466
467 If you are calling a function on an QObject subclass that doesn't
468 live in the current thread and the object might receive events,
469 you must protect all access to your QObject subclass's internal
470 data with a mutex; otherwise, you may experience crashes or other
471 undesired behavior.
472
473 Like other objects, QThread objects live in the thread where the
474 object was created -- \e not in the thread that is created when
475 QThread::run() is called. It is generally unsafe to provide slots
476 in your QThread subclass, unless you protect the member variables
477 with a mutex.
478
479 On the other hand, you can safely emit signals from your
480 QThread::run() implementation, because signal emission is
481 thread-safe.
482
483 \section2 Signals and Slots Across Threads
484
485 Qt supports three types of signal-slot connections:
486
487 \list
488 \o With \l{Qt::DirectConnection}{direct connections}, the
489 slot gets called immediately when the signal is emitted. The
490 slot is executed in the thread that emitted the signal (which
491 is not necessarily the thread where the receiver object
492 lives).
493
494 \o With \l{Qt::QueuedConnection}{queued connections}, the
495 slot is invoked when control returns to the event loop of the
496 thread to which the object belongs. The slot is executed in
497 the thread where the receiver object lives.
498
499 \o With \l{Qt::AutoConnection}{auto connections} (the default),
500 the behavior is the same as with direct connections if
501 the signal is emitted in the thread where the receiver lives;
502 otherwise, the behavior is that of a queued connection.
503 \endlist
504
505 The connection type can be specified by passing an additional
506 argument to \l{QObject::connect()}{connect()}. Be aware that
507 using direct connections when the sender and receiver live in
508 different threads is unsafe if an event loop is running in the
509 receiver's thread, for the same reason that calling any function
510 on an object living in another thread is unsafe.
511
512 QObject::connect() itself is thread-safe.
513
514 The \l{threads/mandelbrot}{Mandelbrot} example uses a queued
515 connection to communicate between a worker thread and the main
516 thread. To avoid freezing the main thread's event loop (and, as a
517 consequence, the application's user interface), all the
518 Mandelbrot fractal computation is done in a separate worker
519 thread. The thread emits a signal when it is done rendering the
520 fractal.
521
522 Similarly, the \l{network/blockingfortuneclient}{Blocking Fortune
523 Client} example uses a separate thread for communicating with
524 a TCP server asynchronously.
525
526 \section1 Threads and Implicit Sharing
527
528 Qt uses an optimization called \l{implicit sharing} for many of
529 its value class, notably QImage and QString. Beginning with Qt 4,
530 implicit shared classes can safely be copied across threads, like
531 any other value classes. They are fully
532 \l{#reentrant}{reentrant}. The implicit sharing is really
533 \e implicit.
534
535 In many people's minds, implicit sharing and multithreading are
536 incompatible concepts, because of the way the reference counting
537 is typically done. Qt, however, uses atomic reference counting to
538 ensure the integrity of the shared data, avoiding potential
539 corruption of the reference counter.
540
541 Note that atomic reference counting does not guarantee
542 \l{#thread-safe}{thread-safety}. Proper locking should be used
543 when sharing an instance of an implicitly shared class between
544 threads. This is the same requirement placed on all
545 \l{#reentrant}{reentrant} classes, shared or not. Atomic reference
546 counting does, however, guarantee that a thread working on its
547 own, local instance of an implicitly shared class is safe. We
548 recommend using \l{Signals and Slots Across Threads}{signals and
549 slots} to pass data between threads, as this can be done without
550 the need for any explicit locking.
551
552 To sum it up, implicitly shared classes in Qt 4 are really \e
553 implicitly shared. Even in multithreaded applications, you can
554 safely use them as if they were plain, non-shared, reentrant
555 value-based classes.
556
557 \section1 Threads and the SQL Module
558
559 A connection can only be used from within the thread that created it.
560 Moving connections between threads or creating queries from a different
561 thread is not supported.
562
563 In addition, the third party libraries used by the QSqlDrivers can impose
564 further restrictions on using the SQL Module in a multithreaded program.
565 Consult the manual of your database client for more information
566
567 \section1 Painting in Threads
568
569 QPainter can be used to paint onto QImage, QPrinter, and QPicture
570 paint devices. Painting onto QPixmaps and QWidgets is \e not
571 supported. On Mac OS X the automatic progress dialog will not be
572 displayed if you are printing from outside the GUI thread.
573
574 Any number of threads can paint at any given time, however only
575 one thread at a time can paint on a given paint device. In other
576 words, two threads can paint at the same time if each paints onto
577 separate QImages, but the two threads cannot paint onto the same
578 QImage at the same time.
579
580 Note that on X11 systems without FontConfig support, Qt cannot
581 render text outside of the GUI thread. You can use the
582 QFontDatabase::supportsThreadedFontRendering() function to detect
583 whether or not font rendering can be used outside the GUI thread.
584
585 \section1 Threads and Rich Text Processing
586
587 The QTextDocument, QTextCursor, and \link richtext.html all
588 related classes\endlink are reentrant.
589
590 Note that a QTextDocument instance created in the GUI thread may
591 contain QPixmap image resources. Use QTextDocument::clone() to
592 create a copy of the document, and pass the copy to another thread for
593 further processing (such as printing).
594
595 \section1 Threads and the SVG module
596
597 The QSvgGenerator and QSvgRenderer classes in the QtSvg module
598 are reentrant.
599
600 \target reading
601 \section1 Recommended Reading
602
603 \list
604 \o \l{Threads Primer: A Guide to Multithreaded Programming}
605 \o \l{Thread Time: The Multithreaded Programming Guide}
606 \o \l{Pthreads Programming: A POSIX Standard for Better Multiprocessing}
607 \o \l{Win32 Multithreaded Programming}
608 \endlist
609*/
Note: See TracBrowser for help on using the repository browser.