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
|
/****************************************************************************
**
**
** Qt thread support
**
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*! \page threads.html
\title Thread Support in Qt
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.
This document is intended for an audience that has knowledge and
experience with multithreaded applications. Recommended reading:
\list
\i \link http://www.amazon.com/exec/obidos/ASIN/0134436989/trolltech/t
Threads Primer: A Guide to Multithreaded Programming\endlink
\i \link http://www.amazon.com/exec/obidos/ASIN/0131900676/trolltech/t
Thread Time: The Multithreaded Programming Guide\endlink
\i \link http://www.amazon.com/exec/obidos/ASIN/1565921151/trolltech/t
Pthreads Programming: A POSIX Standard for Better Multiprocessing (O'Reilly Nutshell)\endlink
\i \link http://www.amazon.com/exec/obidos/ASIN/1565922964/trolltech/t
Win32 Multithreaded Programming\endlink
\endlist
\warning All GUI classes (e.g. QWidget and subclasses), OS kernel
classes (e.g. QProcess), and networking classes, are \e not
thread-safe.
\omit
Classes which \e can be shared across threads are
QBuffer, QCriticalSection, QDir, QFile, QFileInfo, QIODevice,
QLibrary (except on the Mac), QMutex, QPair, QSemaphore, QUuid and
QWaitCondition.
\endomit
\section1 Enabling Thread Support
When Qt is installed on Windows, thread support is an option on some
compilers.
On Mac OS X and Unix, thread support is enabled by adding the
\c{-thread} option when running the \c{configure} 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, \c{libqt-mt} and hence threaded programs must be linked
against this library (with \c{-lqt-mt}) rather than the standard Qt
library.
On both platforms, you should compile with the macro \c
QT_THREAD_SUPPORT defined (e.g. compile with
\c{-DQT_THREAD_SUPPORT}). On Windows, this is usually done by an
entry in \c{qconfig.h}.
\section1 The Thread Classes
The most important class 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.
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:
\code
class MyClass
{
public:
void doStuff( int );
private:
QMutex mutex;
int a;
int b;
};
// This sets a to c, and b to c*2
void MyClass::doStuff( int c )
{
mutex.lock();
a = c;
b = c * 2;
mutex.unlock();
}
\endcode
This ensures that only one thread at a time can be in MyClass::doStuff(),
so \c b will always be equal to \c {c * 2}.
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, \l
QWaitCondition 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 example:
\code
#include <qapplication.h>
#include <qpushbutton.h>
// global condition variable
QWaitCondition mycond;
// Worker class implementation
class Worker : public QPushButton, public QThread
{
Q_OBJECT
public:
Worker(QWidget *parent = 0, const char *name = 0)
: QPushButton(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
QThread::start();
}
public slots:
void slotClicked()
{
// wake up one thread waiting on this condition variable
mycond.wakeOne();
}
protected:
void run()
{
// this method is called by the newly created thread...
while ( TRUE ) {
// 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.wait();
// 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.
int main( int argc, char **argv )
{
QApplication app( argc, argv );
// create a worker... the worker will run a thread when we do
Worker firstworker( 0, "worker" );
app.setMainWidget( &worker );
worker.show();
return app.exec();
}
\endcode
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.
\section1 Thread-safe posting of events
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:
\code
QWidget *mywidget;
QThread::postEvent( mywidget, new QPaintEvent( QRect(0, 0, 100, 100) ) );
\endcode
This (asynchronously) makes mywidget repaint a 100x100
square of its area.
\section1 The Qt library mutex
The Qt library mutex provides a method for calling Qt methods from threads
other than the event thread. For instance:
\code
QApplication *qApp;
QWidget *mywidget;
qApp->lock();
mywidget->setGeometry(0,0,100,100);
QPainter p;
p.begin(mywidget);
p.drawLine(0,0,100,100);
p.end();
qApp->unlock();
\endcode
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.
\section1 Caveats
Some things to watch out for when programming with threads:
\list
\i Don't do any blocking operations while holding the Qt library mutex.
This will freeze up the event loop.
\i Make sure you lock a recursive QMutex as many times as you unlock it,
no more and no less.
\i Lock the Qt application mutex before calling anything except for
the Qt container and tool classes.
\i Be wary of implicitly shared classes; you should
avoid copying them with operator=() between threads. There are plans to
improve this in a future minor or major Qt release.
\i Be wary of Qt classes which were not designed with thread safety in mind;
for instance, QPtrList's API is not thread-safe and if different threads
need to iterate through a QPtrList they should lock before calling
QPtrList::first() and unlock after reaching the end, rather than locking and
unlocking around QPtrList::next().
\i 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.
\i 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.
\i Never call a function that attempts to processEvents() from a
thread other than the GUI thread. This includes QDialog::exec(),
QPopupMenu::exec(), QApplication::processEvents() and others.
\i 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.
\endlist
*/
|