source: trunk/doc/src/frameworks-technologies/threads.qdoc@ 968

Last change on this file since 968 was 846, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

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