Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

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 people who have knowledge and experience of creating multithreaded applications. If you don't have this knowledge, here is some suggested reading to get you started:

Warning: All GUI classes (e.g. QWidget and subclasses), OS kernel classes (e.g. QProcess), and networking classes, are not thread-safe.

QRegExp uses a static cache and is not threadsafe at all, even if the QRegExp object is protected by using QMutex.

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 -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 standard Qt library.

On both platforms, you should compile with the macro QT_THREAD_SUPPORT defined (e.g. compile with -DQT_THREAD_SUPPORT). On Windows, this is usually done by an entry in qconfig.h.

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 example:

    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 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, 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:

    #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...

            for ( ;; ) {
                // 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();
    }
  

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 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:

    QWidget *mywidget;
    QThread::postEvent( mywidget, new QPaintEvent( QRect(0, 0, 100, 100) ) );
  

This (asynchronously) makes mywidget repaint a 100x100 square of its area.

The Qt library mutex

The Qt library mutex provides a method for calling Qt methods from threads other than the event thread. For example:

  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. You must hold the Qt library mutex before calling a GUI-related function from a different thread. 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.

Caveats

Some things to watch out for when programming with threads:

  • Don't do any blocking operations while holding the Qt library mutex. This will freeze up the event loop.

  • Make sure you lock a recursive QMutex as many times as you unlock it, no more and no less.

  • Lock the Qt application mutex before calling anything except for the Qt container and tool classes.

  • Be wary of implicitly shared classes; you should avoid copying them with operator=() between threads. There are plans to improve this in a future Qt release.

  • 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().

  • 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.

  • 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.

  • 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.

  • 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.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 102
  2. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 53
  3. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 81
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 28
  5. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 11
Page suivante
  1. Linus Torvalds : le "C++ est un langage horrible", en justifiant le choix du C pour le système de gestion de version Git 100
  2. Comment prendre en compte l'utilisateur dans vos applications ? Pour un développeur, « 90 % des utilisateurs sont des idiots » 229
  3. Quel est LE livre que tout développeur doit lire absolument ? Celui qui vous a le plus marqué et inspiré 96
  4. Apple cède et s'engage à payer des droits à Nokia, le conflit des brevets entre les deux firmes s'achève 158
  5. Nokia porte à nouveau plainte contre Apple pour violation de sept nouveaux brevets 158
  6. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 102
  7. Quel est le code dont vous êtes le plus fier ? Pourquoi l'avez-vous écrit ? Et pourquoi vous a-t-il donné autant de satisfaction ? 83
Page suivante

Le Qt Developer Network au hasard

Logo

Utiliser QML et QtWebKit avec PySide

Le 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 utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

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 3.0
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 !
 
 
 
 
Partenaires

Hébergement Web