📄 threads.html
字号:
<!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> <font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular" align="center" size=32>Qte</font></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 basicplatform-independent threading classes, a thread-safe way of postingevents and a global Qt library lock that allows you to call Qt methodsfrom different threads.<p><h2>Preface</h2><p> This document is intended for an audience that has knowledge andexperience 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 onsome compilers. The <tt>mkfiles</tt> subdirectory contains build filesfor various compilers - the ones with <tt>-mt</tt> in the name havethread 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 specialways, such as with a special libc, installation will create a separatelibrary, <tt>libqt-mt</tt> and hence threaded programs must be linkedagainst this library (with <tt>-lqt-mt</tt>) rather than the regular Qtlibrary.<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 themeans to start a new thread, which begins execution in yourreimplementation of QThread::run(). This is similar to the Java threadclass.<p> However, a thread class alone is not sufficient. In order to writethreaded programs it is necessary to protect access to data thattwo threads wish to access at once. Therefore there is alsoa QMutex class; a thread can lock the mutex, and while it has it lockedno other thread can lock the mutex; an attempt to do so will block theother 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 wakeit up given a condition; the QWaitCondition class provides this. Threads waitfor the QWaitCondition to indicate that something has happened,blocking until it does. When something happens, <a href="qwaitcondition.html">QWaitCondition</a> can wake up allof the threads waiting for that event or one randomly selected thread (this isthe same functionality as a POSIX Threads condition variable and isimplemented 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 tobe told to do some more work. If the worker thread is already working whenthe button is pressed, nothing will happen. When the thread finishes workingand 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 threadthat pulls events from the window system and dispatches them to widgets.The static method QThread::postEvent posts events from threads other thanthe event thread. The event thread is woken up and the event delivered fromwithin 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 100x100square of its area.<p><h2>The Qt library mutex</h2><p> The Qt library mutex provides a method for calling Qt methods from threadsother 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 resultin unpredictable behavior. Calling a GUI-related function in Qt froma different thread requires holding the Qt library mutex. In thiscontext, all functions that may ultimately access any graphics orwindow system resources are GUI-related. Using container classes,strings and I/O classes does not require any mutex if that object isonly 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 Qtcontainer and tool classes.</li><li>Be wary of classes which are implicitly shared; you should probablydetach() 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 threadsneed to iterate through a QList they should lock before callingQList::first() and unlock after reaching the end, rather than locking andunlocking 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 receiveevents 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. Thisis unnecessary, since all of the QNetwork classes are asynchronous.</li><li>Never call a function that attempts to processEvents from a thread thatis 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
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -