Wednesday, April 7, 2010

[Solution] How to make a Qt thread sleep?

First, consider using sleep(), msleep() or usleep() static methods of QThread class.

However, they are marked as protected, so you can call them only in a QThread subclass.

If for some reason you can't use QThread methods, the following small utility class will help you:

#include <QWaitCondition>
#include <QMutex>

class Sleep
{
 
public:
    
    // Causes the current thread to sleep for msecs milliseconds.
    static void msleep(unsigned long msecs)
    {
        QMutex mutex;
        mutex.lock();
 
        QWaitCondition waitCondition;
        waitCondition.wait(&mutex, msecs);
 
        mutex.unlock();
    }
};

5 comments: