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
|
---|
325 | \title Threads and QObjects
|
---|
326 |
|
---|
327 | \previouspage Reentrancy and Thread Safety
|
---|
328 | \contentspage Thread Support in Qt
|
---|
329 | \nextpage Concurrent Programming
|
---|
330 |
|
---|
331 | QThread inherits QObject. It emits signals to indicate that the
|
---|
332 | thread started or finished executing, and provides a few slots as
|
---|
333 | well.
|
---|
334 |
|
---|
335 | More interesting is that \l{QObject}s can be used in multiple
|
---|
336 | threads, emit signals that invoke slots in other threads, and
|
---|
337 | post events to objects that "live" in other threads. This is
|
---|
338 | possible because each thread is allowed to have its own event
|
---|
339 | loop.
|
---|
340 |
|
---|
341 | Topics:
|
---|
342 |
|
---|
343 | \tableofcontents
|
---|
344 |
|
---|
345 | \section1 QObject Reentrancy
|
---|
346 |
|
---|
347 | QObject is reentrant. Most of its non-GUI subclasses, such as
|
---|
348 | QTimer, QTcpSocket, QUdpSocket, QFtp, and QProcess, are also
|
---|
349 | reentrant, making it possible to use these classes from multiple
|
---|
350 | threads simultaneously. Note that these classes are designed to be
|
---|
351 | created and used from within a single thread; creating an object
|
---|
352 | in one thread and calling its functions from another thread is not
|
---|
353 | guaranteed to work. There are three constraints to be aware of:
|
---|
354 |
|
---|
355 | \list
|
---|
356 | \o \e{The child of a QObject must always be created in the thread
|
---|
357 | where the parent was created.} This implies, among other
|
---|
358 | things, that you should never pass the QThread object (\c
|
---|
359 | this) as the parent of an object created in the thread (since
|
---|
360 | the QThread object itself was created in another thread).
|
---|
361 |
|
---|
362 | \o \e{Event driven objects may only be used in a single thread.}
|
---|
363 | Specifically, this applies to the \l{timers.html}{timer
|
---|
364 | mechanism} and the \l{QtNetwork}{network module}. For example,
|
---|
365 | you cannot start a timer or connect a socket in a thread that
|
---|
366 | is not the \l{QObject::thread()}{object's thread}.
|
---|
367 |
|
---|
368 | \o \e{You must ensure that all objects created in a thread are
|
---|
369 | deleted before you delete the QThread.} This can be done
|
---|
370 | easily by creating the objects on the stack in your
|
---|
371 | \l{QThread::run()}{run()} implementation.
|
---|
372 | \endlist
|
---|
373 |
|
---|
374 | Although QObject is reentrant, the GUI classes, notably QWidget
|
---|
375 | and all its subclasses, are not reentrant. They can only be used
|
---|
376 | from the main thread. As noted earlier, QCoreApplication::exec()
|
---|
377 | must also be called from that thread.
|
---|
378 |
|
---|
379 | In practice, the impossibility of using GUI classes in other
|
---|
380 | threads than the main thread can easily be worked around by
|
---|
381 | putting time-consuming operations in a separate worker thread and
|
---|
382 | displaying the results on screen in the main thread when the
|
---|
383 | worker thread is finished. This is the approach used for
|
---|
384 | implementing the \l{threads/mandelbrot}{Mandelbrot} and
|
---|
385 | the \l{network/blockingfortuneclient}{Blocking Fortune Client}
|
---|
386 | example.
|
---|
387 |
|
---|
388 | \section1 Per-Thread Event Loop
|
---|
389 |
|
---|
390 | Each thread can have its own event loop. The initial thread
|
---|
391 | starts its event loops using QCoreApplication::exec(); other
|
---|
392 | threads can start an event loop using QThread::exec(). Like
|
---|
393 | QCoreApplication, QThread provides an
|
---|
394 | \l{QThread::exit()}{exit(int)} function and a
|
---|
395 | \l{QThread::quit()}{quit()} slot.
|
---|
396 |
|
---|
397 | An event loop in a thread makes it possible for the thread to use
|
---|
398 | certain non-GUI Qt classes that require the presence of an event
|
---|
399 | loop (such as QTimer, QTcpSocket, and QProcess). It also makes it
|
---|
400 | possible to connect signals from any threads to slots of a
|
---|
401 | specific thread. This is explained in more detail in the
|
---|
402 | \l{Signals and Slots Across Threads} section below.
|
---|
403 |
|
---|
404 | \image threadsandobjects.png Threads, objects, and event loops
|
---|
405 |
|
---|
406 | A QObject instance is said to \e live in the thread in which it
|
---|
407 | is created. Events to that object are dispatched by that thread's
|
---|
408 | event loop. The thread in which a QObject lives is available using
|
---|
409 | QObject::thread().
|
---|
410 |
|
---|
411 | Note that for QObjects that are created before QApplication,
|
---|
412 | QObject::thread() returns zero. This means that the main thread
|
---|
413 | will only handle posted events for these objects; other event
|
---|
414 | processing is not done at all for objects with no thread. Use the
|
---|
415 | QObject::moveToThread() function to change the thread affinity for
|
---|
416 | an object and its children (the object cannot be moved if it has a
|
---|
417 | parent).
|
---|
418 |
|
---|
419 | Calling \c delete on a QObject from a thread other than the one
|
---|
420 | that \e owns the object (or accessing the object in other ways) is
|
---|
421 | unsafe, unless you guarantee that the object isn't processing
|
---|
422 | events at that moment. Use QObject::deleteLater() instead, and a
|
---|
423 | \l{QEvent::DeferredDelete}{DeferredDelete} event will be posted,
|
---|
424 | which the event loop of the object's thread will eventually pick
|
---|
425 | up. By default, the thread that \e owns a QObject is the thread
|
---|
426 | that \e creates the QObject, but not after QObject::moveToThread()
|
---|
427 | has been called.
|
---|
428 |
|
---|
429 | If no event loop is running, events won't be delivered to the
|
---|
430 | object. For example, if you create a QTimer object in a thread but
|
---|
431 | never call \l{QThread::exec()}{exec()}, the QTimer will never emit
|
---|
432 | its \l{QTimer::timeout()}{timeout()} signal. Calling
|
---|
433 | \l{QObject::deleteLater()}{deleteLater()} won't work
|
---|
434 | either. (These restrictions apply to the main thread as well.)
|
---|
435 |
|
---|
436 | You can manually post events to any object in any thread at any
|
---|
437 | time using the thread-safe function
|
---|
438 | QCoreApplication::postEvent(). The events will automatically be
|
---|
439 | dispatched by the event loop of the thread where the object was
|
---|
440 | created.
|
---|
441 |
|
---|
442 | Event filters are supported in all threads, with the restriction
|
---|
443 | that the monitoring object must live in the same thread as the
|
---|
444 | monitored object. Similarly, QCoreApplication::sendEvent()
|
---|
445 | (unlike \l{QCoreApplication::postEvent()}{postEvent()}) can only
|
---|
446 | be used to dispatch events to objects living in the thread from
|
---|
447 | which the function is called.
|
---|
448 |
|
---|
449 | \section1 Accessing QObject Subclasses from Other Threads
|
---|
450 |
|
---|
451 | QObject and all of its subclasses are not thread-safe. This
|
---|
452 | includes the entire event delivery system. It is important to keep
|
---|
453 | in mind that the event loop may be delivering events to your
|
---|
454 | QObject subclass while you are accessing the object from another
|
---|
455 | thread.
|
---|
456 |
|
---|
457 | If you are calling a function on an QObject subclass that doesn't
|
---|
458 | live in the current thread and the object might receive events,
|
---|
459 | you must protect all access to your QObject subclass's internal
|
---|
460 | data with a mutex; otherwise, you may experience crashes or other
|
---|
461 | undesired behavior.
|
---|
462 |
|
---|
463 | Like other objects, QThread objects live in the thread where the
|
---|
464 | object was created -- \e not in the thread that is created when
|
---|
465 | QThread::run() is called. It is generally unsafe to provide slots
|
---|
466 | in your QThread subclass, unless you protect the member variables
|
---|
467 | with a mutex.
|
---|
468 |
|
---|
469 | On the other hand, you can safely emit signals from your
|
---|
470 | QThread::run() implementation, because signal emission is
|
---|
471 | thread-safe.
|
---|
472 |
|
---|
473 | \section1 Signals and Slots Across Threads
|
---|
474 |
|
---|
475 | Qt supports these signal-slot connection types:
|
---|
476 |
|
---|
477 | \list
|
---|
478 |
|
---|
479 | \o \l{Qt::AutoConnection}{Auto Connection} (default) The behavior
|
---|
480 | is the same as the Direct Connection, if the emitter and
|
---|
481 | receiver are in the same thread. The behavior is the same as
|
---|
482 | the Queued Connection, if the emitter and receiver are in
|
---|
483 | different threads.
|
---|
484 |
|
---|
485 | \o \l{Qt::DirectConnection}{Direct Connection} The slot is invoked
|
---|
486 | immediately, when the signal is emitted. The slot is executed
|
---|
487 | in the emitter's thread, which is not necessarily the
|
---|
488 | receiver's thread.
|
---|
489 |
|
---|
490 | \o \l{Qt::QueuedConnection}{Queued Connection} The slot is invoked
|
---|
491 | when control returns to the event loop of the receiver's
|
---|
492 | thread. The slot is executed in the receiver's thread.
|
---|
493 |
|
---|
494 | \o \l{Qt::BlockingQueuedConnection}{Blocking Queued Connection}
|
---|
495 | The slot is invoked as for the Queued Connection, except the
|
---|
496 | current thread blocks until the slot returns. \note Using this
|
---|
497 | type to connect objects in the same thread will cause deadlock.
|
---|
498 |
|
---|
499 | \o \l{Qt::UniqueConnection}{Unique Connection} The behavior is the
|
---|
500 | same as the Auto Connection, but the connection is made only if
|
---|
501 | it does not duplicate an existing connection. i.e., if the same
|
---|
502 | signal is already connected to the same slot for the same pair
|
---|
503 | of objects, then the connection is not made and connect()
|
---|
504 | returns false.
|
---|
505 |
|
---|
506 | \endlist
|
---|
507 |
|
---|
508 | The connection type can be specified by passing an additional
|
---|
509 | argument to \l{QObject::connect()}{connect()}. Be aware that
|
---|
510 | using direct connections when the sender and receiver live in
|
---|
511 | different threads is unsafe if an event loop is running in the
|
---|
512 | receiver's thread, for the same reason that calling any function
|
---|
513 | on an object living in another thread is unsafe.
|
---|
514 |
|
---|
515 | QObject::connect() itself is thread-safe.
|
---|
516 |
|
---|
517 | The \l{threads/mandelbrot}{Mandelbrot} example uses a queued
|
---|
518 | connection to communicate between a worker thread and the main
|
---|
519 | thread. To avoid freezing the main thread's event loop (and, as a
|
---|
520 | consequence, the application's user interface), all the
|
---|
521 | Mandelbrot fractal computation is done in a separate worker
|
---|
522 | thread. The thread emits a signal when it is done rendering the
|
---|
523 | fractal.
|
---|
524 |
|
---|
525 | Similarly, the \l{network/blockingfortuneclient}{Blocking Fortune
|
---|
526 | Client} example uses a separate thread for communicating with
|
---|
527 | a TCP server asynchronously.
|
---|
528 | */
|
---|
529 |
|
---|
530 | /*!
|
---|
531 | \page threads-qtconcurrent.html
|
---|
532 | \title Concurrent Programming
|
---|
533 |
|
---|
534 | \previouspage Threads and QObjects
|
---|
535 | \contentspage Thread Support in Qt
|
---|
536 | \nextpage Thread-Support in Qt Modules
|
---|
537 |
|
---|
538 | \target qtconcurrent intro
|
---|
539 |
|
---|
540 | The QtConcurrent namespace provides high-level APIs that make it
|
---|
541 | possible to write multi-threaded programs without using low-level
|
---|
542 | threading primitives such as mutexes, read-write locks, wait
|
---|
543 | conditions, or semaphores. Programs written with QtConcurrent
|
---|
544 | automatically adjust the number of threads used according to the
|
---|
545 | number of processor cores available. This means that applications
|
---|
546 | written today will continue to scale when deployed on multi-core
|
---|
547 | systems in the future.
|
---|
548 |
|
---|
549 | QtConcurrent includes functional programming style APIs for
|
---|
550 | parallel list processing, including a MapReduce and FilterReduce
|
---|
551 | implementation for shared-memory (non-distributed) systems, and
|
---|
552 | classes for managing asynchronous computations in GUI
|
---|
553 | applications:
|
---|
554 |
|
---|
555 | \list
|
---|
556 |
|
---|
557 | \o QtConcurrent::map() applies a function to every item in a container,
|
---|
558 | modifying the items in-place.
|
---|
559 |
|
---|
560 | \o QtConcurrent::mapped() is like map(), except that it returns a new
|
---|
561 | container with the modifications.
|
---|
562 |
|
---|
563 | \o QtConcurrent::mappedReduced() is like mapped(), except that the
|
---|
564 | modified results are reduced or folded into a single result.
|
---|
565 |
|
---|
566 | \o QtConcurrent::filter() removes all items from a container based on the
|
---|
567 | result of a filter function.
|
---|
568 |
|
---|
569 | \o QtConcurrent::filtered() is like filter(), except that it returns a new
|
---|
570 | container with the filtered results.
|
---|
571 |
|
---|
572 | \o QtConcurrent::filteredReduced() is like filtered(), except that the
|
---|
573 | filtered results are reduced or folded into a single result.
|
---|
574 |
|
---|
575 | \o QtConcurrent::run() runs a function in another thread.
|
---|
576 |
|
---|
577 | \o QFuture represents the result of an asynchronous computation.
|
---|
578 |
|
---|
579 | \o QFutureIterator allows iterating through results available via QFuture.
|
---|
580 |
|
---|
581 | \o QFutureWatcher allows monitoring a QFuture using signals-and-slots.
|
---|
582 |
|
---|
583 | \o QFutureSynchronizer is a convenience class that automatically
|
---|
584 | synchronizes several QFutures.
|
---|
585 |
|
---|
586 | \endlist
|
---|
587 |
|
---|
588 | Qt Concurrent supports several STL-compatible container and iterator types,
|
---|
589 | but works best with Qt containers that have random-access iterators, such as
|
---|
590 | QList or QVector. The map and filter functions accept both containers and begin/end iterators.
|
---|
591 |
|
---|
592 | STL Iterator support overview:
|
---|
593 |
|
---|
594 | \table
|
---|
595 | \header
|
---|
596 | \o Iterator Type
|
---|
597 | \o Example classes
|
---|
598 | \o Support status
|
---|
599 | \row
|
---|
600 | \o Input Iterator
|
---|
601 | \o
|
---|
602 | \o Not Supported
|
---|
603 | \row
|
---|
604 | \o Output Iterator
|
---|
605 | \o
|
---|
606 | \o Not Supported
|
---|
607 | \row
|
---|
608 | \o Forward Iterator
|
---|
609 | \o std::slist
|
---|
610 | \o Supported
|
---|
611 | \row
|
---|
612 | \o Bidirectional Iterator
|
---|
613 | \o QLinkedList, std::list
|
---|
614 | \o Supported
|
---|
615 | \row
|
---|
616 | \o Random Access Iterator
|
---|
617 | \o QList, QVector, std::vector
|
---|
618 | \o Supported and Recommended
|
---|
619 | \endtable
|
---|
620 |
|
---|
621 | Random access iterators can be faster in cases where Qt Concurrent is iterating
|
---|
622 | over a large number of lightweight items, since they allow skipping to any point
|
---|
623 | in the container. In addition, using random access iterators allows Qt Concurrent
|
---|
624 | to provide progress information trough QFuture::progressValue() and QFutureWatcher::
|
---|
625 | progressValueChanged().
|
---|
626 |
|
---|
627 | The non in-place modifying functions such as mapped() and filtered() makes a
|
---|
628 | copy of the container when called. If you are using STL containers this copy operation
|
---|
629 | might take some time, in this case we recommend specifying the begin and end iterators
|
---|
630 | for the container instead.
|
---|
631 | */
|
---|
632 |
|
---|
633 | /*!
|
---|
634 | \page threads-modules.html
|
---|
635 | \title Thread-Support in Qt Modules
|
---|
636 |
|
---|
637 | \previouspage Concurrent Programming
|
---|
638 | \contentspage Thread Support in Qt
|
---|
639 |
|
---|
640 | \section1 Threads and the SQL Module
|
---|
641 |
|
---|
642 | A connection can only be used from within the thread that created it.
|
---|
643 | Moving connections between threads or creating queries from a different
|
---|
644 | thread is not supported.
|
---|
645 |
|
---|
646 | In addition, the third party libraries used by the QSqlDrivers can impose
|
---|
647 | further restrictions on using the SQL Module in a multithreaded program.
|
---|
648 | Consult the manual of your database client for more information
|
---|
649 |
|
---|
650 | \section1 Painting in Threads
|
---|
651 |
|
---|
652 | QPainter can be used in a thread to paint onto QImage, QPrinter, and
|
---|
653 | QPicture paint devices. Painting onto QPixmaps and QWidgets is \e not
|
---|
654 | supported. On Mac OS X the automatic progress dialog will not be
|
---|
655 | displayed if you are printing from outside the GUI thread.
|
---|
656 |
|
---|
657 | Any number of threads can paint at any given time, however only
|
---|
658 | one thread at a time can paint on a given paint device. In other
|
---|
659 | words, two threads can paint at the same time if each paints onto
|
---|
660 | separate QImages, but the two threads cannot paint onto the same
|
---|
661 | QImage at the same time.
|
---|
662 |
|
---|
663 | Note that on X11 systems without FontConfig support, Qt cannot
|
---|
664 | render text outside of the GUI thread. You can use the
|
---|
665 | QFontDatabase::supportsThreadedFontRendering() function to detect
|
---|
666 | whether or not font rendering can be used outside the GUI thread.
|
---|
667 |
|
---|
668 | \section1 Threads and Rich Text Processing
|
---|
669 |
|
---|
670 | The QTextDocument, QTextCursor, and \link richtext.html all
|
---|
671 | related classes\endlink are reentrant.
|
---|
672 |
|
---|
673 | Note that a QTextDocument instance created in the GUI thread may
|
---|
674 | contain QPixmap image resources. Use QTextDocument::clone() to
|
---|
675 | create a copy of the document, and pass the copy to another thread for
|
---|
676 | further processing (such as printing).
|
---|
677 |
|
---|
678 | \section1 Threads and the SVG module
|
---|
679 |
|
---|
680 | The QSvgGenerator and QSvgRenderer classes in the QtSvg module
|
---|
681 | are reentrant.
|
---|
682 |
|
---|
683 | \section1 Threads and Implicitly Shared Classes
|
---|
684 |
|
---|
685 | Qt uses an optimization called \l{implicit sharing} for many of
|
---|
686 | its value class, notably QImage and QString. Beginning with Qt 4,
|
---|
687 | implicit shared classes can safely be copied across threads, like
|
---|
688 | any other value classes. They are fully
|
---|
689 | \l{Reentrancy and Thread-Safety}{reentrant}. The implicit sharing
|
---|
690 | is really \e implicit.
|
---|
691 |
|
---|
692 | In many people's minds, implicit sharing and multithreading are
|
---|
693 | incompatible concepts, because of the way the reference counting
|
---|
694 | is typically done. Qt, however, uses atomic reference counting to
|
---|
695 | ensure the integrity of the shared data, avoiding potential
|
---|
696 | corruption of the reference counter.
|
---|
697 |
|
---|
698 | Note that atomic reference counting does not guarantee
|
---|
699 | \l{Reentrancy and Thread-Safety}{thread-safety}. Proper locking should be used
|
---|
700 | when sharing an instance of an implicitly shared class between
|
---|
701 | threads. This is the same requirement placed on all
|
---|
702 | \l{Reentrancy and Thread-Safety}{reentrant} classes, shared or not. Atomic reference
|
---|
703 | counting does, however, guarantee that a thread working on its
|
---|
704 | own, local instance of an implicitly shared class is safe. We
|
---|
705 | recommend using \l{Signals and Slots Across Threads}{signals and
|
---|
706 | slots} to pass data between threads, as this can be done without
|
---|
707 | the need for any explicit locking.
|
---|
708 |
|
---|
709 | To sum it up, implicitly shared classes in Qt 4 are really \e
|
---|
710 | implicitly shared. Even in multithreaded applications, you can
|
---|
711 | safely use them as if they were plain, non-shared, reentrant
|
---|
712 | value-based classes.
|
---|
713 | */
|
---|