1 | /****************************************************************************
|
---|
2 | **
|
---|
3 | ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
|
---|
4 | ** All rights reserved.
|
---|
5 | ** Contact: Nokia Corporation (qt-info@nokia.com)
|
---|
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 qt-info@nokia.com.
|
---|
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
|
---|
467 |
|
---|
468 | Qt supports these signal-slot connection types:
|
---|
469 |
|
---|
470 | \list
|
---|
471 |
|
---|
472 | \o \l{Qt::AutoConnection}{Auto Connection} (default) If the signal is
|
---|
473 | emitted in the thread which the receiving object has affinity then
|
---|
474 | the behavior is the same as the Direct Connection. Otherwise,
|
---|
475 | the behavior is the same as the Queued Connection."
|
---|
476 |
|
---|
477 | \o \l{Qt::DirectConnection}{Direct Connection} The slot is invoked
|
---|
478 | immediately, when the signal is emitted. The slot is executed
|
---|
479 | in the emitter's thread, which is not necessarily the
|
---|
480 | receiver's thread.
|
---|
481 |
|
---|
482 | \o \l{Qt::QueuedConnection}{Queued Connection} The slot is invoked
|
---|
483 | when control returns to the event loop of the receiver's
|
---|
484 | thread. The slot is executed in the receiver's thread.
|
---|
485 |
|
---|
486 | \o \l{Qt::BlockingQueuedConnection}{Blocking Queued Connection}
|
---|
487 | The slot is invoked as for the Queued Connection, except the
|
---|
488 | current thread blocks until the slot returns. \note Using this
|
---|
489 | type to connect objects in the same thread will cause deadlock.
|
---|
490 |
|
---|
491 | \o \l{Qt::UniqueConnection}{Unique Connection} The behavior is the
|
---|
492 | same as the Auto Connection, but the connection is made only if
|
---|
493 | it does not duplicate an existing connection. i.e., if the same
|
---|
494 | signal is already connected to the same slot for the same pair
|
---|
495 | of objects, then the connection is not made and connect()
|
---|
496 | returns false.
|
---|
497 |
|
---|
498 | \endlist
|
---|
499 |
|
---|
500 | The connection type can be specified by passing an additional
|
---|
501 | argument to \l{QObject::connect()}{connect()}. Be aware that
|
---|
502 | using direct connections when the sender and receiver live in
|
---|
503 | different threads is unsafe if an event loop is running in the
|
---|
504 | receiver's thread, for the same reason that calling any function
|
---|
505 | on an object living in another thread is unsafe.
|
---|
506 |
|
---|
507 | QObject::connect() itself is thread-safe.
|
---|
508 |
|
---|
509 | The \l{threads/mandelbrot}{Mandelbrot} example uses a queued
|
---|
510 | connection to communicate between a worker thread and the main
|
---|
511 | thread. To avoid freezing the main thread's event loop (and, as a
|
---|
512 | consequence, the application's user interface), all the
|
---|
513 | Mandelbrot fractal computation is done in a separate worker
|
---|
514 | thread. The thread emits a signal when it is done rendering the
|
---|
515 | fractal.
|
---|
516 |
|
---|
517 | Similarly, the \l{network/blockingfortuneclient}{Blocking Fortune
|
---|
518 | Client} example uses a separate thread for communicating with
|
---|
519 | a TCP server asynchronously.
|
---|
520 | */
|
---|
521 |
|
---|
522 | /*!
|
---|
523 | \page threads-qtconcurrent.html
|
---|
524 | \title Concurrent Programming
|
---|
525 |
|
---|
526 | \previouspage Threads and QObjects
|
---|
527 | \contentspage Thread Support in Qt
|
---|
528 | \nextpage Thread-Support in Qt Modules
|
---|
529 |
|
---|
530 | \target qtconcurrent intro
|
---|
531 |
|
---|
532 | The QtConcurrent namespace provides high-level APIs that make it
|
---|
533 | possible to write multi-threaded programs without using low-level
|
---|
534 | threading primitives such as mutexes, read-write locks, wait
|
---|
535 | conditions, or semaphores. Programs written with QtConcurrent
|
---|
536 | automatically adjust the number of threads used according to the
|
---|
537 | number of processor cores available. This means that applications
|
---|
538 | written today will continue to scale when deployed on multi-core
|
---|
539 | systems in the future.
|
---|
540 |
|
---|
541 | QtConcurrent includes functional programming style APIs for
|
---|
542 | parallel list processing, including a MapReduce and FilterReduce
|
---|
543 | implementation for shared-memory (non-distributed) systems, and
|
---|
544 | classes for managing asynchronous computations in GUI
|
---|
545 | applications:
|
---|
546 |
|
---|
547 | \list
|
---|
548 |
|
---|
549 | \o QtConcurrent::map() applies a function to every item in a container,
|
---|
550 | modifying the items in-place.
|
---|
551 |
|
---|
552 | \o QtConcurrent::mapped() is like map(), except that it returns a new
|
---|
553 | container with the modifications.
|
---|
554 |
|
---|
555 | \o QtConcurrent::mappedReduced() is like mapped(), except that the
|
---|
556 | modified results are reduced or folded into a single result.
|
---|
557 |
|
---|
558 | \o QtConcurrent::filter() removes all items from a container based on the
|
---|
559 | result of a filter function.
|
---|
560 |
|
---|
561 | \o QtConcurrent::filtered() is like filter(), except that it returns a new
|
---|
562 | container with the filtered results.
|
---|
563 |
|
---|
564 | \o QtConcurrent::filteredReduced() is like filtered(), except that the
|
---|
565 | filtered results are reduced or folded into a single result.
|
---|
566 |
|
---|
567 | \o QtConcurrent::run() runs a function in another thread.
|
---|
568 |
|
---|
569 | \o QFuture represents the result of an asynchronous computation.
|
---|
570 |
|
---|
571 | \o QFutureIterator allows iterating through results available via QFuture.
|
---|
572 |
|
---|
573 | \o QFutureWatcher allows monitoring a QFuture using signals-and-slots.
|
---|
574 |
|
---|
575 | \o QFutureSynchronizer is a convenience class that automatically
|
---|
576 | synchronizes several QFutures.
|
---|
577 |
|
---|
578 | \endlist
|
---|
579 |
|
---|
580 | Qt Concurrent supports several STL-compatible container and iterator types,
|
---|
581 | but works best with Qt containers that have random-access iterators, such as
|
---|
582 | QList or QVector. The map and filter functions accept both containers and begin/end iterators.
|
---|
583 |
|
---|
584 | STL Iterator support overview:
|
---|
585 |
|
---|
586 | \table
|
---|
587 | \header
|
---|
588 | \o Iterator Type
|
---|
589 | \o Example classes
|
---|
590 | \o Support status
|
---|
591 | \row
|
---|
592 | \o Input Iterator
|
---|
593 | \o
|
---|
594 | \o Not Supported
|
---|
595 | \row
|
---|
596 | \o Output Iterator
|
---|
597 | \o
|
---|
598 | \o Not Supported
|
---|
599 | \row
|
---|
600 | \o Forward Iterator
|
---|
601 | \o std::slist
|
---|
602 | \o Supported
|
---|
603 | \row
|
---|
604 | \o Bidirectional Iterator
|
---|
605 | \o QLinkedList, std::list
|
---|
606 | \o Supported
|
---|
607 | \row
|
---|
608 | \o Random Access Iterator
|
---|
609 | \o QList, QVector, std::vector
|
---|
610 | \o Supported and Recommended
|
---|
611 | \endtable
|
---|
612 |
|
---|
613 | Random access iterators can be faster in cases where Qt Concurrent is iterating
|
---|
614 | over a large number of lightweight items, since they allow skipping to any point
|
---|
615 | in the container. In addition, using random access iterators allows Qt Concurrent
|
---|
616 | to provide progress information trough QFuture::progressValue() and QFutureWatcher::
|
---|
617 | progressValueChanged().
|
---|
618 |
|
---|
619 | The non in-place modifying functions such as mapped() and filtered() makes a
|
---|
620 | copy of the container when called. If you are using STL containers this copy operation
|
---|
621 | might take some time, in this case we recommend specifying the begin and end iterators
|
---|
622 | for the container instead.
|
---|
623 | */
|
---|
624 |
|
---|
625 | /*!
|
---|
626 | \page threads-modules.html
|
---|
627 | \title Thread-Support in Qt Modules
|
---|
628 |
|
---|
629 | \previouspage Concurrent Programming
|
---|
630 | \contentspage Thread Support in Qt
|
---|
631 |
|
---|
632 | \section1 Threads and the SQL Module
|
---|
633 |
|
---|
634 | A connection can only be used from within the thread that created it.
|
---|
635 | Moving connections between threads or creating queries from a different
|
---|
636 | thread is not supported.
|
---|
637 |
|
---|
638 | In addition, the third party libraries used by the QSqlDrivers can impose
|
---|
639 | further restrictions on using the SQL Module in a multithreaded program.
|
---|
640 | Consult the manual of your database client for more information
|
---|
641 |
|
---|
642 | \section1 Painting in Threads
|
---|
643 |
|
---|
644 | QPainter can be used in a thread to paint onto QImage, QPrinter, and
|
---|
645 | QPicture paint devices. Painting onto QPixmaps and QWidgets is \e not
|
---|
646 | supported. On Mac OS X the automatic progress dialog will not be
|
---|
647 | displayed if you are printing from outside the GUI thread.
|
---|
648 |
|
---|
649 | Any number of threads can paint at any given time, however only
|
---|
650 | one thread at a time can paint on a given paint device. In other
|
---|
651 | words, two threads can paint at the same time if each paints onto
|
---|
652 | separate QImages, but the two threads cannot paint onto the same
|
---|
653 | QImage at the same time.
|
---|
654 |
|
---|
655 | Note that on X11 systems without FontConfig support, Qt cannot
|
---|
656 | render text outside of the GUI thread. You can use the
|
---|
657 | QFontDatabase::supportsThreadedFontRendering() function to detect
|
---|
658 | whether or not font rendering can be used outside the GUI thread.
|
---|
659 |
|
---|
660 | \section1 Threads and Rich Text Processing
|
---|
661 |
|
---|
662 | The QTextDocument, QTextCursor, and \link richtext.html all
|
---|
663 | related classes\endlink are reentrant.
|
---|
664 |
|
---|
665 | Note that a QTextDocument instance created in the GUI thread may
|
---|
666 | contain QPixmap image resources. Use QTextDocument::clone() to
|
---|
667 | create a copy of the document, and pass the copy to another thread for
|
---|
668 | further processing (such as printing).
|
---|
669 |
|
---|
670 | \section1 Threads and the SVG module
|
---|
671 |
|
---|
672 | The QSvgGenerator and QSvgRenderer classes in the QtSvg module
|
---|
673 | are reentrant.
|
---|
674 |
|
---|
675 | \section1 Threads and Implicitly Shared Classes
|
---|
676 |
|
---|
677 | Qt uses an optimization called \l{implicit sharing} for many of
|
---|
678 | its value class, notably QImage and QString. Beginning with Qt 4,
|
---|
679 | implicit shared classes can safely be copied across threads, like
|
---|
680 | any other value classes. They are fully
|
---|
681 | \l{Reentrancy and Thread-Safety}{reentrant}. The implicit sharing
|
---|
682 | is really \e implicit.
|
---|
683 |
|
---|
684 | In many people's minds, implicit sharing and multithreading are
|
---|
685 | incompatible concepts, because of the way the reference counting
|
---|
686 | is typically done. Qt, however, uses atomic reference counting to
|
---|
687 | ensure the integrity of the shared data, avoiding potential
|
---|
688 | corruption of the reference counter.
|
---|
689 |
|
---|
690 | Note that atomic reference counting does not guarantee
|
---|
691 | \l{Reentrancy and Thread-Safety}{thread-safety}. Proper locking should be used
|
---|
692 | when sharing an instance of an implicitly shared class between
|
---|
693 | threads. This is the same requirement placed on all
|
---|
694 | \l{Reentrancy and Thread-Safety}{reentrant} classes, shared or not. Atomic reference
|
---|
695 | counting does, however, guarantee that a thread working on its
|
---|
696 | own, local instance of an implicitly shared class is safe. We
|
---|
697 | recommend using \l{Signals and Slots Across Threads}{signals and
|
---|
698 | slots} to pass data between threads, as this can be done without
|
---|
699 | the need for any explicit locking.
|
---|
700 |
|
---|
701 | To sum it up, implicitly shared classes in Qt 4 are really \e
|
---|
702 | implicitly shared. Even in multithreaded applications, you can
|
---|
703 | safely use them as if they were plain, non-shared, reentrant
|
---|
704 | value-based classes.
|
---|
705 | */
|
---|