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