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

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

trunk: Merged in qt 4.6.1 sources.

  • Property svn:eol-style set to native
File size: 29.7 KB
RevLine 
[556]1/****************************************************************************
2**
3** Copyright (C) 2009 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:LGPL$
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
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this 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 have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42/*!
43 \group thread
44 \title Threading Classes
45*/
46
47/*!
48 \page threads.html
49 \title Thread Support in Qt
50 \brief A detailed discussion of thread handling in Qt.
51
52 \ingroup frameworks-technologies
53
54 \nextpage Starting Threads with QThread
55
56 Qt provides thread support in the form of platform-independent
57 threading classes, a thread-safe way of posting events, and
58 signal-slot connections across threads. This makes it easy to
59 develop portable multithreaded Qt applications and take advantage
60 of multiprocessor machines. Multithreaded programming is also a
61 useful paradigm for performing time-consuming operations without
62 freezing the user interface of an application.
63
64 Earlier versions of Qt offered an option to build the library
65 without thread support. Since Qt 4.0, threads are always enabled.
66
67 \section1 Topics:
68
69 \list
70 \o \l{Recommended Reading}
71 \o \l{The Threading Classes}
72 \o \l{Starting Threads with QThread}
73 \o \l{Synchronizing Threads}
74 \o \l{Reentrancy and Thread-Safety}
75 \o \l{Threads and QObjects}
76 \o \l{Concurrent Programming}
77 \o \l{Thread-Support in Qt Modules}
78 \endlist
79
80 \section1 Recommended Reading
81
82 This document is intended for an audience that has knowledge of,
83 and experience with, multithreaded applications. If you are new
84 to threading see our Recommended Reading list:
85
86 \list
87 \o \l{Threads Primer: A Guide to Multithreaded Programming}
88 \o \l{Thread Time: The Multithreaded Programming Guide}
89 \o \l{Pthreads Programming: A POSIX Standard for Better Multiprocessing}
90 \o \l{Win32 Multithreaded Programming}
91 \endlist
92
93 \section1 The Threading Classes
94
95 These classes are relevant to threaded applications.
96
97 \annotatedlist thread
98
99\omit
100 \list
101 \o QThread provides the means to start a new thread.
102 \o QThreadStorage provides per-thread data storage.
103 \o QThreadPool manages a pool of threads that run QRunnable objects.
104 \o QRunnable is an abstract class representing a runnable object.
105 \o QMutex provides a mutual exclusion lock, or mutex.
106 \o QMutexLocker is a convenience class that automatically locks
107 and unlocks a QMutex.
108 \o QReadWriteLock provides a lock that allows simultaneous read access.
109 \o QReadLocker and QWriteLocker are convenience classes that automatically
110 lock and unlock a QReadWriteLock.
111 \o QSemaphore provides an integer semaphore (a generalization of a mutex).
112 \o QWaitCondition provides a way for threads to go to sleep until
113 woken up by another thread.
114 \o QAtomicInt provides atomic operations on integers.
115 \o QAtomicPointer provides atomic operations on pointers.
116 \endlist
117\endomit
118
119 \note Qt's threading classes are implemented with native threading APIs;
120 e.g., Win32 and pthreads. Therefore, they can be used with threads of the
121 same native API.
122*/
123
124/*!
125 \page threads-starting.html
126 \title Starting Threads with QThread
127
128 \contentspage Thread Support in Qt
129 \nextpage Synchronizing Threads
130
131 A QThread instance represents a thread and provides the means to
132 \l{QThread::start()}{start()} a thread, which will then execute the
133 reimplementation of QThread::run(). The \c run() implementation is for a
134 thread what the \c main() entry point is for the application. All code
135 executed in a call stack that starts in the \c run() function is executed
136 by the new thread, and the thread finishes when the function returns.
137 QThread emits signals to indicate that the thread started or finished
138 executing.
139
140 \section1 Creating a Thread
141
142 To create a thread, subclass QThread and reimplement its
143 \l{QThread::run()}{run()} function. For example:
144
145 \snippet doc/src/snippets/threads/threads.h 0
146 \codeline
147 \snippet doc/src/snippets/threads/threads.cpp 0
148 \snippet doc/src/snippets/threads/threads.cpp 1
149 \dots
150 \snippet doc/src/snippets/threads/threads.cpp 2
151
152 \section1 Starting a Thread
153
154 Then, create an instance of the thread object and call
155 QThread::start(). Note that you must create the QApplication (or
156 QCoreApplication) object before you can create a QThread.
157
158 The function will return immediately and the
159 main thread will continue. The code that appears in the
160 \l{QThread::run()}{run()} reimplementation will then be executed
161 in a separate thread.
162
163 Creating threads is explained in more detail in the QThread
164 documentation.
165
166 Note that QCoreApplication::exec() must always be called from the
167 main thread (the thread that executes \c{main()}), not from a
168 QThread. In GUI applications, the main thread is also called the
169 GUI thread because it's the only thread that is allowed to
170 perform GUI-related operations.
171*/
172
173/*!
174 \page threads-synchronizing.html
175 \title Synchronizing Threads
176
177 \previouspage Starting Threads with QThread
178 \contentspage Thread Support in Qt
179 \nextpage Reentrancy and Thread-Safety
180
181 The QMutex, QReadWriteLock, QSemaphore, and QWaitCondition
182 classes provide means to synchronize threads. While the main idea
183 with threads is that they should be as concurrent as possible,
184 there are points where threads must stop and wait for other
185 threads. For example, if two threads try to access the same
186 global variable simultaneously, the results are usually
187 undefined.
188
189 QMutex provides a mutually exclusive lock, or mutex. At most one
190 thread can hold the mutex at any time. If a thread tries to
191 acquire the mutex while the mutex is already locked, the thread will
192 be put to sleep until the thread that currently holds the mutex
193 unlocks it. Mutexes are often used to protect accesses to shared
194 data (i.e., data that can be accessed from multiple threads
195 simultaneously). In the \l{Reentrancy and Thread-Safety} section
196 below, we will use it to make a class thread-safe.
197
198 QReadWriteLock is similar to QMutex, except that it distinguishes
199 between "read" and "write" access to shared data and allows
200 multiple readers to access the data simultaneously. Using
201 QReadWriteLock instead of QMutex when it is possible can make
202 multithreaded programs more concurrent.
203
204 QSemaphore is a generalization of QMutex that protects a certain
205 number of identical resources. In contrast, a mutex protects
206 exactly one resource. The \l{threads/semaphores}{Semaphores}
207 example shows a typical application of semaphores: synchronizing
208 access to a circular buffer between a producer and a consumer.
209
210 QWaitCondition allows a thread to wake up other threads when some
211 condition has been met. One or many threads can block waiting for
212 a QWaitCondition to set a condition with
213 \l{QWaitCondition::wakeOne()}{wakeOne()} or
214 \l{QWaitCondition::wakeAll()}{wakeAll()}. Use
215 \l{QWaitCondition::wakeOne()}{wakeOne()} to wake one randomly
216 selected event or \l{QWaitCondition::wakeAll()}{wakeAll()} to
217 wake them all. The \l{threads/waitconditions}{Wait Conditions}
218 example shows how to solve the producer-consumer problem using
219 QWaitCondition instead of QSemaphore.
220
221 Note that Qt's synchronization classes rely on the use of properly
222 aligned pointers. For instance, you cannot use packed classes with
223 MSVC.
224*/
225
226/*!
227 \page threads-reentrancy.html
228 \title Reentrancy and Thread-Safety
229
230 \keyword reentrant
231 \keyword thread-safe
232
233 \previouspage Synchronizing Threads
234 \contentspage Thread Support in Qt
235 \nextpage Threads and QObjects
236
237 Throughout the documentation, the terms \e{reentrant} and
238 \e{thread-safe} are used to mark classes and functions to indicate
239 how they can be used in multithread applications:
240
241 \list
242 \o A \e thread-safe function can be called simultaneously from
243 multiple threads, even when the invocations use shared data,
244 because all references to the shared data are serialized.
245 \o A \e reentrant function can also be called simultaneously from
246 multiple threads, but only if each invocation uses its own data.
247 \endlist
248
249 Hence, a \e{thread-safe} function is always \e{reentrant}, but a
250 \e{reentrant} function is not always \e{thread-safe}.
251
252 By extension, a class is said to be \e{reentrant} if its member
253 functions can be called safely from multiple threads, as long as
254 each thread uses a \e{different} instance of the class. The class
255 is \e{thread-safe} if its member functions can be called safely
256 from multiple threads, even if all the threads use the \e{same}
257 instance of the class.
258
259 C++ classes are often reentrant, simply because they only access
260 their own member data. Any thread can call a member function on an
261 instance of a reentrant class, as long as no other thread can call
262 a member function on the \e{same} instance of the class at the
263 same time. For example, the \c Counter class below is reentrant:
264
265 \snippet doc/src/snippets/threads/threads.cpp 3
266 \snippet doc/src/snippets/threads/threads.cpp 4
267
268 The class isn't thread-safe, because if multiple threads try to
269 modify the data member \c n, the result is undefined. This is
270 because the \c ++ and \c -- operators aren't always atomic.
271 Indeed, they usually expand to three machine instructions:
272
273 \list 1
274 \o Load the variable's value in a register.
275 \o Increment or decrement the register's value.
276 \o Store the register's value back into main memory.
277 \endlist
278
279 If thread A and thread B load the variable's old value
280 simultaneously, increment their register, and store it back, they
281 end up overwriting each other, and the variable is incremented
282 only once!
283
284 Clearly, the access must be serialized: Thread A must perform
285 steps 1, 2, 3 without interruption (atomically) before thread B
286 can perform the same steps; or vice versa. An easy way to make
287 the class thread-safe is to protect all access to the data
288 members with a QMutex:
289
290 \snippet doc/src/snippets/threads/threads.cpp 5
291 \snippet doc/src/snippets/threads/threads.cpp 6
292
293 The QMutexLocker class automatically locks the mutex in its
294 constructor and unlocks it when the destructor is invoked, at the
295 end of the function. Locking the mutex ensures that access from
296 different threads will be serialized. The \c mutex data member is
297 declared with the \c mutable qualifier because we need to lock
298 and unlock the mutex in \c value(), which is a const function.
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 Qt Classes are only documented as \e{thread-safe} if they
314 are intended to be used by multiple threads.
315
316 \note Terminology in the multithreading domain isn't entirely
317 standardized. POSIX uses definitions of reentrant and thread-safe
318 that are somewhat different for its C APIs. When using other
319 object-oriented C++ class libraries with Qt, be sure the
320 definitions are understood.
321*/
322
323/*!
324 \page threads-qobject.html