<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- /tmp/qt-3.0-reggie-28534/qt-x11-free-3.0.2/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"><!-- 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: #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> 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 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> <b>Warning:</b> All GUI classes (e.g. <a href="qwidget.html">QWidget</a> and subclasses), OS kernel classes (e.g. <a href="qprocess.html">QProcess</a>), and networking classes, are <em>not</em> thread-safe. <p> <h2> Enabling Thread Support </h2> <a name="1"></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="2"></a><p> The most important class is <a href="qthread.html">QThread</a>; this 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> 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 <a href="qmutex.html">QMutex</a> 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#lock">lock</a>(); a = c; b = c * 2; mutex.<a href="qmutex.html#unlock">unlock</a>(); } </pre> <p> This ensures that only one thread at a time can be in MyClass::doStuff(), so <tt>b</tt> will always be equal to <tt>c * 2</tt>. <p> Also necessary is a method for threads to wait for another thread to wake it up given a condition; the <a href="qwaitcondition.html">QWaitCondition</a> 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 example: <p> <pre> #include <<a href="qapplication-h.html">qapplication.h</a>> #include <<a href="qpushbutton-h.html">qpushbutton.h</a>> // global condition variable <a href="qwaitcondition.html">QWaitCondition</a> mycond; // Worker class implementation class Worker : public <a href="qpushbutton.html">QPushButton</a>, public QThread { <a href="metaobjects.html#Q_OBJECT">Q_OBJECT</a> public: Worker(QWidget *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 QThread::<a href="qthread.html#start">start</a>(); } public slots: void slotClicked() { // wake up one thread waiting on this condition variable mycond.<a href="qwaitcondition.html#wakeOne">wakeOne</a>(); } 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-><a href="qapplication.html#lock">lock</a>(); setCaption( "Waiting" ); qApp-><a href="qapplication.html#unlock">unlock</a>(); // wait until we are told to continue mycond.<a href="qwaitcondition.html#wait">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-><a href="qapplication.html#lock">lock</a>(); setCaption( "Working!" ); qApp-><a href="qapplication.html#unlock">unlock</a>(); // 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 ) { <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#setMainWidget">setMainWidget</a>( &worker ); worker.show(); return app.<a href="qapplication.html#exec">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 <a href="qwaitcondition.html#wait">QWaitCondition::wait</a>() again, then it can be started. <p> <h2> Thread-safe posting of events </h2> <a name="3"></a><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; QThread::<a href="qthread.html#postEvent">postEvent</a>( mywidget, new <a href="qpaintevent.html">QPaintEvent</a>( QRect(0, 0, 100, 100) ) ); </pre> <p> This (asynchronously) makes mywidget repaint a 100x100 square of its area. <p> <h2> The Qt library mutex </h2> <a name="4"></a><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#lock">lock</a>(); mywidget-><a href="qwidget.html#setGeometry">setGeometry</a>(0,0,100,100); <a href="qpainter.html">QPainter</a> p; p.<a href="qpainter.html#begin">begin</a>(mywidget); 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> 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> <a name="5"></a><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. <p> <li> Make sure you lock a recursive <a href="qmutex.html">QMutex</a> as many times as you unlock it, no more and no less. <p> <li> Lock the Qt application mutex before calling anything except for the Qt container and tool classes. <p> <li> Be wary of <a href="shclass.html#implicitly-shared">implicitly shared</a> classes; you should avoid copying them with operator=() between threads. There are plans to improve this in a future minor or major Qt release. <p> <li> Be wary of Qt classes which were not designed with thread safety in mind; for instance, <a href="qptrlist.html">QPtrList</a>'s API is not thread-safe and if different threads need to iterate through a QPtrList they should lock before calling <a href="qptrlist.html#first">QPtrList::first</a>() and unlock after reaching the end, rather than locking and unlocking around <a href="qptrlist.html#next">QPtrList::next</a>(). <p> <li> Be sure to create objects that inherit or use <a href="qwidget.html">QWidget</a>, <a href="qtimer.html">QTimer</a> and <a href="qsocketnotifier.html">QSocketNotifier</a> 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. <p> <li> Similar to the above, only use the QNetwork classes inside the GUI thread. A common question asked is if a <a href="qsocket.html">QSocket</a> can be used in multiple threads. This is unnecessary, since all of the QNetwork classes are asynchronous. <p> <li> Never call a function that attempts to processEvents() from a thread other than the GUI thread. This includes <a href="qdialog.html#exec">QDialog::exec</a>(), <a href="qpopupmenu.html#exec">QPopupMenu::exec</a>(), <a href="qapplication.html#processEvents">QApplication::processEvents</a>() and others. <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> </ul> <p> <!-- eof --> <p><address><hr><div align=center> <table width=100% cellspacing=0 border=0><tr> <td>Copyright © 2001 <a href="http://www.trolltech.com">Trolltech</a><td><a href="http://www.trolltech.com/trademarks.html">Trademarks</a> <td align=right><div align=right>Qt version 3.0.2</div> </table></div></address></body> </html>