Sleep problem without QThread class



  • how to make my program sleep for 100 ms without using Qthread class??



  • maybe:
    -#include <qwaitcondition.h>-

    -QWaitCondition sleep;-
    -sleep.wait(1000); // one seconds-

    ahh, sorry this was ok for Qt 3, but for Qt 4 the wait() function is changed... (you need a mutex too)



  • You either use QTest
    @
    QTest::qSleep(100); // no event processing
    QTest::qWait(100); // event processing
    @
    or you use QWaitCondition / QMutex
    @
    QWaitCondition waitCondition;
    QMutex mutex;

    waitCondition.wait(&mutex, 100);
    @
    or you use QThread.
    @
    class Thread : public QThread
    {
    public:
    static void msleep(int ms)
    {
    QThread::msleep(ms);
    }
    };

    Thread::msleep(100);
    @

    However, having to do so in an event-driven application is usually a clear indicator for a broken design.



  • Is there any specific reason not to use QThread::sleep() ?



  • Yes, it is protected.



  • [quote author="Lukas Geyer" date="1325612918"]
    or you use QThread
    [/quote]

    Hm... What about the (pure virtual) run() function?



  • [quote author="broadpeak" date="1325618245"]
    Hm... What about the (pure virtual) run() function?[/quote]

    It is indeed virtual, but not pure. The default implementation simply calls exec() (which doesn't even matter in our case, as the thread isn't started). QThread::msleep() causes the current thread to sleep.



  • On unix like machins (including the Mac):

    @
    #include <unistd.h>

    // sleep for 5 seconds
    sleep(5);

    // sleep for another 5 seconds (5,000,000 microseconds)
    usleep(5000000);
    @

    On Windows:
    @
    // sleep for 5 seconds (5000 milliseconds)
    Sleep(5000);
    @

    Or copy the implementation of QTest::qSleep():

    @
    #ifdef Q_OS_WIN
    #include <windows.h> // for Sleep
    #else
    #include <time.h>
    #endif

    void mySleep(int ms)
    {
    if(ms <= 0)
    return

    #ifdef Q_OS_WIN
    Sleep(uint(ms));
    #else
    struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
    nanosleep(&ts, NULL);
    #endif
    }
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.