Important: Please read the Qt Code of Conduct -

[SOLVED]Is there a problem with the following non-blocking sleep function?

  • @
    QEventLoop loop;
    QTimer::singleShot(time_to_wait, &loop, SLOT(quit()));

    I'm using this approach to create a wait function that does not freeze the window, in my tests it's working! So what I want to know is if this is a good approach or not.

  • Moderators

    Looks good to me. :)

    Not sure why you would want to non-block sleep a thread but it would accomplish what you want.

  • Thanks for your answer! :)

    An explanation: I need this because I need to check a value of a variable using while and only goes away when the desired value is got, also I need my thread free to handle some signals during the loop execution(the condition expected by the while is got when some signal is triggered and processed) and when the desired value is got, finally the loop ends.

    And I need the loop to prevent the class goes away, btw the function is the class destructor.

  • Moderators

    Interesting design idea..

    Could you not just send a signal your class catches when the value is done being updated and then that slot could call this->deleteLater() thus cleaning itself up?

    It seems like the while loop is an extreme way to check that variable. Obviously hard on your cpu which is why you need that sleep.

  • I came across this old topic looking if there was a ready-made solution to "active-but-not-busy-wait", i.e. a function or class that works like sleep() but without the blocking aspect. IOW, not a real sleep, more like a slumber :)

    Here's my take based on the OP's solution:

    class QSlumber
        QSlumber(qreal seconds)
            if (seconds > 0) {
                QEventLoop loop;
                QTimer::singleShot(seconds * 1000, &loop, SLOT(quit()));
        static qreal during(qreal seconds)
            QElapsedTimer duration;
            QSlumber sleep(seconds);
            return duration.elapsed() / 1000.0;

Log in to reply