[SOLVED]Is there a problem with the following non-blocking sleep function?
-
wrote on 15 Sept 2014, 23:44 last edited by
@
QEventLoop loop;
QTimer::singleShot(time_to_wait, &loop, SLOT(quit()));
loop.exec();
@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.
-
wrote on 15 Sept 2014, 23:53 last edited by
Looks good to me. :)
Not sure why you would want to non-block sleep a thread but it would accomplish what you want.
-
wrote on 16 Sept 2014, 00:15 last edited by
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.
-
wrote on 16 Sept 2014, 22:28 last edited by
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.
-
wrote on 2 Aug 2018, 08:32 last edited by
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 { public: QSlumber(qreal seconds) { if (seconds > 0) { QEventLoop loop; QTimer::singleShot(seconds * 1000, &loop, SLOT(quit())); loop.exec(); } } static qreal during(qreal seconds) { QElapsedTimer duration; duration.start(); QSlumber sleep(seconds); return duration.elapsed() / 1000.0; } };