Thread Support in QtIn 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.
PrefaceThis document is intended for an audience that has knowledge and experience with multithreaded applications. Recommended reading:
Enabling thread supportWhen Qt is installed on Windows, thread support is an option on some compilers. The mkfiles subdirectory contains build files for various compilers - the ones with -mt in the name have thread support enabled. On Unix, thread support is enabled by adding the -thread option when running the 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, libqt-mt and hence threaded programs must be linked against this library (with -lqt-mt) rather than the regular Qt library. On both platforms, you should compile with the macro QT_THREAD_SUPPORT defined (eg. compile with -DQT_THREAD_SUPPORT). On Windows, this is usually done by an entry in qconfig.h.
The Qt thread classesThe 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. 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:
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(); } This ensures that only one thread at a time can be in MyClass::doStuff(), so b will always be equal to a*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, 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 instance:
#include <qapplication.h> #include <qpushbutton.h> // global condition variable QWaitCondition mycond; // Worker class implementation class Worker : public QPushButton, public QThread { 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(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.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. 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(); } 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.
Thread-safe posting of eventsIn 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:
QWidget *mywidget; QThread::postEvent( mywidget, new QPaintEvent( QRect(0, 0, 100, 100) ) ); This (asynchronously) makes mywidget to repaint a 100x100 square of its area.
The Qt library mutexThe Qt library mutex provides a method for calling Qt methods from threads other than the event thread. For instance:
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(); 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.
CaveatsSome things to watch out for when programming with threads:
|
Publicité
Best OfActualités les plus luesSemaine
Mois
Année
Le Qt Developer Network au hasardLes basesLe Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.
CommunautéRessources
Liens utilesContact
Qt dans le magazine |
Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. | Qt 2.3 | |
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD. | ||
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP ! |
Copyright © 2000-2012 - www.developpez.com