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
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Qt Toolkit - Thread Support in Qt</title><style type="text/css"><!--
h3.fn,span.fn { margin-left: 1cm; text-indent: -1cm; }
a:link { color: #004faf; text-decoration: none }
a:visited { color: #672967; text-decoration: none }body { background: white; color: black; }
--></style></head><body bgcolor="#ffffff">
<p>
<table width="100%">
<tr><td><a href="index.html">
<img width="100" height="100" src="qtlogo.png"
alt="Home" border="0"><img width="100"
height="100" src="face.png" alt="Home" border="0">
</a><td valign=top><div align=right><img src="dochead.png" width="472" height="27"><br>
<a href="classes.html"><b>Classes</b></a>
-<a href="annotated.html">Annotated</a>
- <a href="hierarchy.html">Tree</a>
-<a href="functions.html">Functions</a>
-<a href="index.html">Home</a>
-<a href="topicals.html"><b>Structure</b></a>
</div>
</table>
<h1 align=center> Thread Support in Qt</h1><br clear="all">
In version 2.2, Qt introduced thread support to Qt in the shape of some 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>
<h2>Preface</h2>
<p>
This document is intended for an audience that has knowledge and
experience with multithreaded applications. Recommended reading:
<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>
<h2>Enabling thread support</h2>
<p>
When Qt is installed on Windows, thread support is an option on
some compilers. The <tt>mkfiles</tt> subdirectory contains build files
for various compilers - the ones with <tt>-mt</tt> in the name have
thread support enabled.
<p>
On 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 regular Qt
library.
<p>
On both platforms, you should compile with the macro <tt>QT_THREAD_SUPPORT</tt>
defined (eg. compile with <tt>-DQT_THREAD_SUPPORT</tt>).
On Windows, this is usually done by an entry in <tt>qconfig.h</tt>.
<p>
<h2>The Qt thread classes</h2>
<p>
The most important class, obviously, is QThread; this provides the
means to start a new thread, which begins execution in your
reimplementation of QThread::run(). This is similar to the Java thread
class.
<p>
However, a thread class alone is not sufficient. In order to write
threaded programs it is necessary to protect access to data that
two threads wish to access at once. Therefore there is also
a QMutex class; a thread can lock the mutex, and while it has it locked
no other thread can lock the mutex; an attempt to do so will block the
other thread until the mutex is released. For instance:
<p>
<pre> class MyClass {
public:
void doStuff(int);
private:
<a href="qmutex.html">QMutex</a> mutex;
int a;
int b;
};
// This sets a to c, and b to c*2
void MyClass::doStuff(int c)
{
mutex.<a href="qmutex.html#4e6e5d">lock</a>();
a=c;
b=c*2;
mutex.<a href="qmutex.html#da15c3">unlock</a>();
}
</pre>
<p>
This ensures that only one thread at a time can be in MyClass::doStuff(),
so b will always be equal to a*2.
<p>
Also necessary is a method for threads to wait for another thread to wake
it up given a condition; the QWaitCondition class provides this. Threads wait
for the QWaitCondition to indicate that something has happened,
blocking until it does. When something happens, <a href="qwaitcondition.html">QWaitCondition</a> can wake up all
of the threads waiting for that event or one randomly selected thread (this is
the same functionality as a POSIX Threads condition variable and is
implemented as one on Unix). For instance:
<p>
<pre> #include <qapplication.h>
#include <qpushbutton.h>
// global condition variable
<a href="qwaitcondition.html">QWaitCondition</a> mycond;
// Worker class implementation
class Worker : public QPushButton, public QThread
{
public:
Worker(<a href="qwidget.html">QWidget</a> *parent = 0, const char *name = 0)
: <a href="qpushbutton.html">QPushButton</a>(parent, name)
{
setText("Start Working");
// connect the clicked() signal inherited from QPushButton to our
// slotClicked() method
connect(this, SIGNAL(clicked()), SLOT(slotClicked()));
// call the start() method inherited from QThread... this starts
// execution of the thread immediately
<a href="qthread.html#536ef2">QThread::start</a>();
}
public slots:
void slotClicked()
{
// wake up one thread waiting on this condition variable
mycond.<a href="qwaitcondition.html#57c32e">wakeOne</a>();
}
protected:
void run()
{
// this method is called by the newly created thread...
while(1) {
// lock the application mutex, and set the caption of
// the window to indicate that we are waiting to
// start working
qApp->lock();
setCaption("Waiting");
qApp->unlock();
// wait until we are told to continue
mycond.<a href="qwaitcondition.html#d24199">wait</a>();
// if we get here, we have been woken by another
// thread... let's set the caption to indicate
// that we are working
qApp->lock();
setCaption("Working!");
qApp->unlock();
// this could take a few seconds, minutes, hours, etc.
// since it is in a separate thread from the GUI thread
// the gui will not stop processing events...
do_complicated_thing();
}
}
};
// main thread - all GUI events are handled by this thread.
main(int argc, char **argv)
{
<a href="qapplication.html">QApplication</a> app(argc, argv);
// create a worker... the worker will run a thread when we do
Worker firstworker(0, "worker");
app.<a href="qapplication.html#7ad759">setMainWidget</a>(&worker);
worker.show();
return app.<a href="qapplication.html#84c7bf">exec</a>();
}
</pre>
<p>
This program will wake up the worker thread whenever you press the button;
the thread will go off and do some work and then go back to waiting to
be told to do some more work. If the worker thread is already working when
the button is pressed, nothing will happen. When the thread finishes working
and calls QWaitCondition::wait() again, then it can be started.
<p>
<h2>Thread-safe posting of events</h2>
<p>
In Qt, one thread is always the event thread - that is, the thread
that pulls events from the window system and dispatches them to widgets.
The static method QThread::postEvent posts events from threads other than
the event thread. The event thread is woken up and the event delivered from
within the event thread just as a normal window system event is. For instance,
you could force a widget to repaint from a different thread by doing the following:
<p>
<pre> <a href="qwidget.html">QWidget</a> *mywidget;
<a href="qthread.html#f0670e">QThread::postEvent</a>( mywidget, new <a href="qpaintevent.html">QPaintEvent</a>( <a href="qrect.html">QRect</a>(0, 0, 100, 100) ) );
</pre>
<p>
This (asynchronously) makes mywidget to repaint a 100x100
square of its area.
<p>
<h2>The Qt library mutex</h2>
<p>
The Qt library mutex provides a method for calling Qt methods from threads
other than the event thread. For instance:
<p>
<pre> <a href="qapplication.html">QApplication</a> *qApp;
<a href="qwidget.html">QWidget</a> *mywidget;
qApp-><a href="qapplication.html#e7d891">lock</a>();
mywidget-><a href="qwidget.html#9ede68">setGeometry</a>(0,0,100,100);
<a href="qpainter.html">QPainter</a> p;
p.<a href="qpainter.html#02ed5d">begin</a>(mywidget);
p.<a href="qpainter.html#e3a489">drawLine</a>(0,0,100,100);
p.<a href="qpainter.html#365784">end</a>();
qApp-><a href="qapplication.html#cc10ca">unlock</a>();
</pre>
<p>
Calling a function in Qt without holding a mutex will generally result
in unpredictable behavior. Calling a GUI-related function in Qt from
a different thread requires holding the Qt library mutex. In this
context, all functions that may ultimately access any graphics or
window system resources are GUI-related. Using container classes,
strings and I/O classes does not require any mutex if that object is
only accessed by one thread.
<p>
<h2>Caveats</h2>
<p>
Some things to watch out for when programming with threads:
<ul>
<li>Don't do any blocking operations while holding the Qt library mutex.
This will freeze up the event loop.</li>
<li>Make sure you lock a recursive QMutex as many times as you unlock it,
no more and no less.</li>
<li>Lock the Qt application mutex before calling anything but the Qt
container and tool classes.</li>
<li>Be wary of classes which are implicitly shared; you should probably
detach() them if you need to assign them between threads.</li>
<li>Be wary of Qt classes which were not designed with thread safety in mind;
for instance, QList's API is not thread-safe and if different threads
need to iterate through a QList they should lock before calling
QList::first() and unlock after reaching the end, rather than locking and
unlocking around QList::next().</li>
<li>Be sure to create objects that inherit or use QWidget, QTimer and
QSocketNotifier objects only in the GUI thread. On some platforms,
such objects created in a thread other than the GUI thread will never receive
events from the underlying window system.</li>
<li>Similar to the above, only use the QNetwork classes inside the GUI thread.
A common question asked is if a QSocket can be used in multiple threads. This
is unnecessary, since all of the QNetwork classes are asynchronous.</li>
<li>Never call a function that attempts to processEvents from a thread that
is not the GUI thread. This includes QDialog::exec(), QPopupMenu::exec(),
QApplication::processEvents() and others.</li>
</ul>
<p><address><hr><div align="center">
<table width="100%" cellspacing="0" border="0"><tr>
<td>Copyright 2001 Trolltech<td><a href="http://www.trolltech.com/trademarks.html">Trademarks</a>
<td align="right"><div align="right">Qt version 2.3.2</div>
</table></div></address></body></html>
|