1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-x11-free-3.3.8/doc/threads.doc:36 -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Thread Support in Qt</title>
<style type="text/css"><!--
fn { margin-left: 1cm; text-indent: -1cm; }
a:link { color: #004faf; text-decoration: none }
a:visited { color: #672967; text-decoration: none }
body { background: #ffffff; color: black; }
--></style>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr bgcolor="#E5E5E5">
<td valign=center>
<a href="index.html">
<font color="#004faf">Home</font></a>
| <a href="classes.html">
<font color="#004faf">All Classes</font></a>
| <a href="mainclasses.html">
<font color="#004faf">Main Classes</font></a>
| <a href="annotated.html">
<font color="#004faf">Annotated</font></a>
| <a href="groups.html">
<font color="#004faf">Grouped Classes</font></a>
| <a href="functions.html">
<font color="#004faf">Functions</font></a>
</td>
<td align="right" valign="center"><img src="logo32.png" align="right" width="64" height="32" border="0"></td></tr></table><h1 align=center>Thread Support in Qt</h1>
<p> <!-- toc -->
<ul>
<li><a href="#1"> Introduction
</a>
<li><a href="#2"> Enabling Thread Support
</a>
<li><a href="#3"> The Thread Classes
</a>
<li><a href="#4"> Important Definitions
</a>
<li><a href="#5"> Thread-safe Event Posting
</a>
<li><a href="#6"> Threads and QObject subclasses
</a>
<li><a href="#7"> The Qt Library Mutex
</a>
<li><a href="#8"> Threads and Signals and Slots
</a>
<li><a href="#9"> Threads and Shared Data
</a>
<li><a href="#10"> Threads and the SQL Module
</a>
<li><a href="#11"> Caveats
</a>
<li><a href="#12"> Recommended Reading
</a>
</ul>
<!-- endtoc -->
<p> <h2> Introduction
</h2>
<a name="1"></a><p> Qt provides thread support in the form of basic platform-independent
threading classes, a thread-safe way of posting events, and a global
Qt library lock that allows you to call Qt methods from different
threads.
<p> This document is intended for an audience that has knowledge of, and
experience with, multithreaded applications. If you are new to
threading see our <a href="#reading">Recommended Reading</a> list.
<p> <h2> Enabling Thread Support
</h2>
<a name="2"></a><p> When Qt is installed on Windows, thread support is an option on some
compilers.
<p> On Mac OS X and Unix, thread support is enabled by adding the
<tt>-thread</tt> option when running the <tt>configure</tt> script. On Unix
platforms where multithreaded programs must be linked in special ways,
such as with a special libc, installation will create a separate
library, <tt>libqt-mt</tt> and hence threaded programs must be linked
against this library (with <tt>-lqt-mt</tt>) rather than the standard Qt
library.
<p> On both platforms, you should compile with the macro <tt>QT_THREAD_SUPPORT</tt> defined (e.g. compile with
<tt>-DQT_THREAD_SUPPORT</tt>). On Windows, this is usually done by an
entry in <tt>qconfig.h</tt>.
<p> <h2> The Thread Classes
</h2>
<a name="3"></a><p> These classes are built into the Qt library when thread support is enabled:
<p> <ul>
<li> <a href="qthread.html">QThread</a> - Provides the means to start a new thread, which begins
execution in your reimplementation of <a href="qthread.html#run">QThread::run</a>(). This is similar
to the Java thread class.
<p> <li> <a href="qthreadstorage.html">QThreadStorage</a> - Provides per-thread data storage. This class can
only be used with threads started with QThread; it cannot be used with
threads started with platform-specific APIs.
<p> <li> <a href="qmutex.html">QMutex</a> - Provides a mutual exclusion lock (also know as a mutex).
<li> <a href="qmutexlocker.html">QMutexLocker</a> - A convenience class which automatically locks and
unlocks a QMutex. QMutexLocker is useful in complicated code, or in
code which uses exceptions. See the documentation for more details.
<li> <a href="qwaitcondition.html">QWaitCondition</a> - Provides a way for threads to go to sleep until
woken up by another thread.
<li> <a href="qsemaphore.html">QSemaphore</a> - Provides a simple integer semaphore.
</ul>
<p> <h2> Important Definitions
</h2>
<a name="4"></a><p> <a name="reentrant"></a>
<a name="threadsafe"></a>
<p> When using Qt in a multithreaded program, it is important to
understand the definition of the terms <em>reentrant</em> and <em>thread-safe</em>:
<p> <ul>
<li> <em>reentrant</em> - Describes a function which can be called
simultaneously by multiple threads when each invocation of the
function references unique data. Calling a reentrant function
simultaneously with the same data is not safe, and such invocations
should be serialized.
<li> <em>thread-safe</em> - Describes a function which can be called
simultaneously by multiple threads when each invocation references
shared data. Calling a thread-safe function simultaneously with the
same data is safe, since all access to the shared data are serialized.
</ul>
<p> Note that Qt provides both implictly and <a href="shclass.html#explicitly-shared">explicitly shared</a>
classes. For more information, see the <a href="threads.html#threads-shared">Threads and Shared Data</a>
section.
<p> Most C++ member functions are inherently reentrant, since they only
reference class member data. Any thread can call such a member
function on an instance, as long as no other thread is calling a
member function on the same instance. For example, given the class <tt>Number</tt> below:
<p> <pre>
class Number
{
public:
inline Number( int n ) : num( n ) { }
inline int number() const { return num; }
inline void setNumber( int n ) { num = n; }
private:
int num;
};
</pre>
<p> The methods <tt>Number::number()</tt> and <tt>Number::setNumber()</tt> are
reentrant, since they only reference unique data. Only one thread at
a time can call member functions on each instance of <tt>Number</tt>.
However, multiple threads can call member functions on separate
instances of <tt>Number</tt>.
<p> Thread-safe functions usually use a mutex (e.g a <a href="qmutex.html">QMutex</a>) to serialize
access to shared data. Because of this, thread-safe functions are
usually slower than reentrant functions, because of the extra overhead
of locking and unlocking the mutex. For example, given the class <tt>Counter</tt> below:
<p> <pre>
class Counter
{
public:
inline Counter() { ++instances; }
inline ~Counter() { --instances; }
private:
static int instances;
};
</pre>
<p> Since the modifications of the static <tt>instances</tt> integer are not
serialized, this class is not thread-safe. So make it threadsafe, a
mutex must be used:
<p> <pre>
class Counter
{
public:
inline Counter()
{
mutex.lock();
++instances;
mutex.unlock();
}
...
private:
static QMutex mutex;
static int instances;
};
</pre>
<p> <h2> Thread-safe Event Posting
</h2>
<a name="5"></a><p> In Qt, one thread is always the GUI or event thread. This is the
thread that creates a <a href="qapplication.html">QApplication</a> object and calls
<a href="qapplication.html#exec">QApplication::exec</a>(). This is also the initial thread that calls
main() at program start. This thread is the only thread that is
allowed to perform GUI operations, including generating and receiving
events from the window system. Qt does not support creating
QApplication and running the event loop (with QApplication::exec()) in
a secondary thread. You must create the QApplication object and call
QApplication::exec() from the main() function in your program.
<p> Threads that wish to display data in a widget cannot modify the widget
directly, so they must post an event to the widget using
<a href="qapplication.html#postEvent">QApplication::postEvent</a>(). The event will be delivered later on by
the GUI thread.
<p> Normally, the programmer would like to include some information in the
event sent to the widget. See the documentation for <a href="qcustomevent.html">QCustomEvent</a> for
more information on user-defined events.
<p> <h2> Threads and <a href="qobject.html">QObject</a> subclasses
</h2>
<a name="6"></a><p> The QObject class itself is <em>reentrant</em>. However, certain rules
apply when creating and using QObjects in a thread that is not the GUI
thread.
<p> <ol type=1>
<p> <li> <em>None</em> of the QObject based classes included in the Qt library are
<em>reentrant</em>. This includes all widgets (e.g. <a href="qwidget.html">QWidget</a> and
subclasses), OS kernel classes (e.g. <a href="qprocess.html">QProcess</a>, <a href="qaccel.html">QAccel</a>, <a href="qtimer.html">QTimer</a>), and
all networking classes (e.g. <a href="qsocket.html">QSocket</a>, <a href="qdns.html">QDns</a>).
<p> <li> QObject and all of its subclasses are <em>not</em> <em>thread-safe</em>. This
includes the entire event delivery system. It is important to
remember that the GUI thread may be delivering events to your QObject
subclass while you are accessing the object from another thread. If
you are using QObject in a thread that is not the GUI thread, and you
are handling events sent to this object, you <em>must</em> protect all
access to your data with a mutex; otherwise you may experience crashes
or other undesired behavior.
<p> <li> As a corollary to the above, deleting a <a href="qobject.html">QObject</a> while pending
events are waiting to be delivered can cause a crash. You must not
delete the QObject directly from a thread that is not the GUI thread.
Use the <a href="qobject.html#deleteLater">QObject::deleteLater</a>() method instead, which will cause the
event loop to delete the object after all pending events have been
delivered to the object.
<p> </ol>
<p> <h2> The Qt Library Mutex
</h2>
<a name="7"></a><p> <a href="qapplication.html">QApplication</a> includes a mutex that is used to protect access to window
system functions. This mutex is locked while the event loop is
running (e.g. during event delivery) and unlocked when the eventloop
goes to sleep. Note: The Qt event loop is recursive, and the library
mutex is <em>not</em> unlocked when re-entering the event loop (e.g. when
executing a modal dialog with <a href="qdialog.html#exec">QDialog::exec</a>()).
<p> If another thread locks the Qt library mutex, then the event loop will
stop processing events, and the locking thread may do simple GUI
operations. Operations such as creating a <a href="qpainter.html">QPainter</a> and drawing a line
are examples of simple GUI operations:
<p> <pre>
...
qApp-><a href="qapplication.html#lock">lock</a>();
<a href="qpainter.html">QPainter</a> p;
p.<a href="qpainter.html#begin">begin</a>( mywidget );
p.<a href="qpainter.html#setPen">setPen</a>( QColor( "red" ) );
p.<a href="qpainter.html#drawLine">drawLine</a>( 0,0,100,100 );
p.<a href="qpainter.html#end">end</a>();
qApp-><a href="qapplication.html#unlock">unlock</a>();
...
</pre>
<p> Any operations that generate events must not be called by any thread
other than the GUI thread. Examples of such operations are:
<p> <ul>
<li> creating a <a href="qwidget.html">QWidget</a>, <a href="qtimer.html">QTimer</a>, <a href="qsocketnotifier.html">QSocketNotifier</a>, <a href="qsocket.html">QSocket</a> or other network class.
<li> moving, resizing, showing or hiding a QWidget.
<li> starting or stoping a QTimer.
<li> enabling or disabling a QSocketNotifier.
<li> using a QSocket or other network class.
</ul>
<p> Events generated by these operations will be lost on some platforms.
<p> <h2> Threads and Signals and Slots
</h2>
<a name="8"></a><p> The Signals and Slots mechanism can be used in separate threads, as
long as the rules for <a href="qobject.html">QObject</a> based classes are followed. The Signals
and Slots mechanism is synchronous: when a signal is emitted, all
slots are called immediately. The slots are executed in the thread
context that emitted the signal.
<p> <b>Warning:</b> Slots that generate window system events or use window system
functions <em>must</em> <em>not</em> be connected to a signal that is emitted from
a thread that is not the GUI thread. See the Qt Library Mutex section
above for more details.
<p> <a name="threads-shared"></a>
<h2> Threads and Shared Data
</h2>
<a name="9"></a><p> Qt provides many <a href="shclass.html#implicitly-shared">implicitly shared</a> and explicitly shared classes. In
a multithreaded program, multiple instances of a shared class can
reference shared data, which is dangerous if one or more threads
attempt to modify the data. Qt provides the <a href="qdeepcopy.html">QDeepCopy</a> class, which
ensures that shared classes reference unique data.
<p> See the description of <a href="shclass.html">implicit sharing</a> for more
information.
<p> <a name="threads-sql"></a>
<h2> Threads and the SQL Module
</h2>
<a name="10"></a><p> A connection can only be used from within the thread that created it.
Moving connections between threads or creating queries from a different
thread is not supported.
<p> In addition, the third party libraries used by the QSqlDrivers can impose
further restrictions on using the SQL Module in a multithreaded program.
Consult the manual of your database client for more information.
<p> <h2> Caveats
</h2>
<a name="11"></a><p> Some things to watch out for when programming with threads:
<p> <ul>
<p> <li> As mentioned above, <a href="qobject.html">QObject</a> based classes are neither thread-safe
nor reentrant. This includes all widgets (e.g. <a href="qwidget.html">QWidget</a> and
subclasses), OS kernel classes (e.g. <a href="qprocess.html">QProcess</a>, <a href="qaccel.html">QAccel</a>), and all
networking classes (e.g. <a href="qsocket.html">QSocket</a>, <a href="qdns.html">QDns</a>).
<p> <li> Deleting a QObject while pending events are waiting to be delivered
will cause a crash. If you are creating QObjects in a thread that is
not the GUI thread and posting events to these objects, you should not
delete the QObject directly. Use the <a href="qobject.html#deleteLater">QObject::deleteLater</a>() method
instead, which will cause the event loop to delete the object after
all pending events have been delivered to the object.
<p> <li> Don't do any blocking operations while holding the Qt library
mutex. This will freeze up the event loop.
<p> <li> Make sure you unlock a recursive <a href="qmutex.html">QMutex</a> as many times as you lock
it, no more and no less.
<p> <li> Don't mix the normal Qt library and the threaded Qt library in your
application. This means that if your application uses the threaded Qt
library, you should not link with the normal Qt library, dynamically
load the normal Qt library or dynamically load another library or
plugin that depends on the normal Qt library. On some systems, doing
this can corrupt the static data used in the Qt library.
<p> <li> Qt does not support creating <a href="qapplication.html">QApplication</a> and running the event
loop (with <a href="qapplication.html#exec">QApplication::exec</a>()) in a secondary thread. You must
create the QApplication object and call QApplication::exec() from the
main() function in your program.
<p> </ul>
<p> <a name="reading"></a>
<h2> Recommended Reading
</h2>
<a name="12"></a><p> <ul>
<li> <a href="http://www.amazon.com/exec/obidos/ASIN/0134436989/trolltech/t">Threads Primer: A Guide to Multithreaded Programming</a>
<li> <a href="http://www.amazon.com/exec/obidos/ASIN/0131900676/trolltech/t">Thread Time: The Multithreaded Programming Guide</a>
<li> <a href="http://www.amazon.com/exec/obidos/ASIN/1565921151/trolltech/t">Pthreads Programming: A POSIX Standard for Better Multiprocessing (O'Reilly Nutshell)</a>
<li> <a href="http://www.amazon.com/exec/obidos/ASIN/1565922964/trolltech/t">Win32 Multithreaded Programming</a>
</ul>
<p>
<!-- eof -->
<p><address><hr><div align=center>
<table width=100% cellspacing=0 border=0><tr>
<td>Copyright © 2007
<a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a>
<td align=right><div align=right>Qt 3.3.8</div>
</table></div></address></body>
</html>
|