Qt World Summit: Register Today!

QThread::sleep() question

  • There are three variants of QThread::sleep():

    QThread::sleep(); // seconds
    QThread::msleep(); // msec
    QThread::usleep(); // usec

    Are these merely convenience forms allowing you to specify arbitrary sleep durations in these units, or is the input argument assumed to be within a range? For example, if is use:

    quint sleep_msec = 6,000;
    QThread::msleep(sleep_msec );

    Will this work without an overflow since the sleep_msec value is greater than one second?

    The documentation doesn't specify.


  • Hi! For Unix-like systems, the definition is in qthread_unix.cpp:

    void QThread::sleep(unsigned long secs)
        qt_nanosleep(makeTimespec(secs, 0));
    void QThread::msleep(unsigned long msecs)
        qt_nanosleep(makeTimespec(msecs / 1000, msecs % 1000 * 1000 * 1000));
    void QThread::usleep(unsigned long usecs)
        qt_nanosleep(makeTimespec(usecs / 1000 / 1000, usecs % (1000*1000) * 1000));

    qt_nanosleep is defined in qelapsedtimer_unix.cpp:

    void qt_nanosleep(timespec amount)
        // We'd like to use clock_nanosleep.
        // But clock_nanosleep is from POSIX.1-2001 and both are *not*
        // affected by clock changes when using relative sleeps, even for
        // CLOCK_REALTIME.
        // nanosleep is POSIX.1-1993
        int r;
        EINTR_LOOP(r, nanosleep(&amount, &amount));

    So all three functions call nanosleep(2) in the end.

    makeTimespec is also defined in qthread_unix.cpp:

    static timespec makeTimespec(time_t secs, long nsecs)
        struct timespec ts;
        ts.tv_sec = secs;
        ts.tv_nsec = nsecs;
        return ts;

  • Excellent! Thank you! I really should download the source code for Qt ;-)

Log in to reply