Can you implement a timer without a âsleepâ in it using standard c++/c++11 only?
Clash Royale CLAN TAG#URR8PPP
up vote
31
down vote
favorite
I have the following code (hand-copied in):
// Simple stop watch class basically takes "now" as the start time and
// returns the diff when asked for.
class stop_watch ...
// global var
std::thread timer_thread;
void start_timer(int timeout_ms)
timer_thread = std::thread([timeout_ms, this]()
stop_watch sw;
while (sw.get_elapsed_time() < timeout_ms)
// Here is the sleep to stop from hammering a CPU
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Do timeout things here...
std::cout << "timed out!" << std::endl;
)
I did not want to get too bogged down in the detail of the class I writing so this is a very cut-down version. The full class calls a function call-back and has a variable to cancel the timer etc...
I just wanted to focus on the "sleep" part. Can I implement something like this without a sleep or is there a better way to do it? - or is sleep perfectly good? - I was of the opinion that sleeps are generally a sign of bad design (I have read that a few places)... but I can't think of a way to implement a timer without one :(
Additional Note: The timer should have the requirement to be able to be stopped/woken at any time. Just adding that for clarity because it appears to affect what kind of solution to go for. In my original code (not this snippet) I used an atomic bool flag that can break out of the loop.
c++ c++11 timer
 |Â
show 5 more comments
up vote
31
down vote
favorite
I have the following code (hand-copied in):
// Simple stop watch class basically takes "now" as the start time and
// returns the diff when asked for.
class stop_watch ...
// global var
std::thread timer_thread;
void start_timer(int timeout_ms)
timer_thread = std::thread([timeout_ms, this]()
stop_watch sw;
while (sw.get_elapsed_time() < timeout_ms)
// Here is the sleep to stop from hammering a CPU
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Do timeout things here...
std::cout << "timed out!" << std::endl;
)
I did not want to get too bogged down in the detail of the class I writing so this is a very cut-down version. The full class calls a function call-back and has a variable to cancel the timer etc...
I just wanted to focus on the "sleep" part. Can I implement something like this without a sleep or is there a better way to do it? - or is sleep perfectly good? - I was of the opinion that sleeps are generally a sign of bad design (I have read that a few places)... but I can't think of a way to implement a timer without one :(
Additional Note: The timer should have the requirement to be able to be stopped/woken at any time. Just adding that for clarity because it appears to affect what kind of solution to go for. In my original code (not this snippet) I used an atomic bool flag that can break out of the loop.
c++ c++11 timer
6
You probably have a design issue and want to use astd::future
instead. It has methodswait_for
andwait_until
.
â Henri Menke
Aug 13 at 7:21
How accurate does the timer need to be? Nothing wrong with usingsleep_for
in this way.
â Bathsheba
Aug 13 at 7:21
2
sleep is bad for "synchronize" multiple thread together, your usage might be fine.
â Jarod42
Aug 13 at 7:21
1
in "standard c++11" this is about all you have. If you widen your net to include posix then you can build an io loop based on pselect et al. boost.asio is built (sort of) this way.
â Richard Hodges
Aug 13 at 7:22
@HenriMenke I like the idea of wait_until(...), but I am thinking that if you wanted to exit the wait_until(...) part early I am not sure how you would do that?
â code_fodder
Aug 13 at 7:47
 |Â
show 5 more comments
up vote
31
down vote
favorite
up vote
31
down vote
favorite
I have the following code (hand-copied in):
// Simple stop watch class basically takes "now" as the start time and
// returns the diff when asked for.
class stop_watch ...
// global var
std::thread timer_thread;
void start_timer(int timeout_ms)
timer_thread = std::thread([timeout_ms, this]()
stop_watch sw;
while (sw.get_elapsed_time() < timeout_ms)
// Here is the sleep to stop from hammering a CPU
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Do timeout things here...
std::cout << "timed out!" << std::endl;
)
I did not want to get too bogged down in the detail of the class I writing so this is a very cut-down version. The full class calls a function call-back and has a variable to cancel the timer etc...
I just wanted to focus on the "sleep" part. Can I implement something like this without a sleep or is there a better way to do it? - or is sleep perfectly good? - I was of the opinion that sleeps are generally a sign of bad design (I have read that a few places)... but I can't think of a way to implement a timer without one :(
Additional Note: The timer should have the requirement to be able to be stopped/woken at any time. Just adding that for clarity because it appears to affect what kind of solution to go for. In my original code (not this snippet) I used an atomic bool flag that can break out of the loop.
c++ c++11 timer
I have the following code (hand-copied in):
// Simple stop watch class basically takes "now" as the start time and
// returns the diff when asked for.
class stop_watch ...
// global var
std::thread timer_thread;
void start_timer(int timeout_ms)
timer_thread = std::thread([timeout_ms, this]()
stop_watch sw;
while (sw.get_elapsed_time() < timeout_ms)
// Here is the sleep to stop from hammering a CPU
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Do timeout things here...
std::cout << "timed out!" << std::endl;
)
I did not want to get too bogged down in the detail of the class I writing so this is a very cut-down version. The full class calls a function call-back and has a variable to cancel the timer etc...
I just wanted to focus on the "sleep" part. Can I implement something like this without a sleep or is there a better way to do it? - or is sleep perfectly good? - I was of the opinion that sleeps are generally a sign of bad design (I have read that a few places)... but I can't think of a way to implement a timer without one :(
Additional Note: The timer should have the requirement to be able to be stopped/woken at any time. Just adding that for clarity because it appears to affect what kind of solution to go for. In my original code (not this snippet) I used an atomic bool flag that can break out of the loop.
c++ c++11 timer
c++ c++11 timer
edited Aug 19 at 13:04
asked Aug 13 at 7:17
code_fodder
4,67543567
4,67543567
6
You probably have a design issue and want to use astd::future
instead. It has methodswait_for
andwait_until
.
â Henri Menke
Aug 13 at 7:21
How accurate does the timer need to be? Nothing wrong with usingsleep_for
in this way.
â Bathsheba
Aug 13 at 7:21
2
sleep is bad for "synchronize" multiple thread together, your usage might be fine.
â Jarod42
Aug 13 at 7:21
1
in "standard c++11" this is about all you have. If you widen your net to include posix then you can build an io loop based on pselect et al. boost.asio is built (sort of) this way.
â Richard Hodges
Aug 13 at 7:22
@HenriMenke I like the idea of wait_until(...), but I am thinking that if you wanted to exit the wait_until(...) part early I am not sure how you would do that?
â code_fodder
Aug 13 at 7:47
 |Â
show 5 more comments
6
You probably have a design issue and want to use astd::future
instead. It has methodswait_for
andwait_until
.
â Henri Menke
Aug 13 at 7:21
How accurate does the timer need to be? Nothing wrong with usingsleep_for
in this way.
â Bathsheba
Aug 13 at 7:21
2
sleep is bad for "synchronize" multiple thread together, your usage might be fine.
â Jarod42
Aug 13 at 7:21
1
in "standard c++11" this is about all you have. If you widen your net to include posix then you can build an io loop based on pselect et al. boost.asio is built (sort of) this way.
â Richard Hodges
Aug 13 at 7:22
@HenriMenke I like the idea of wait_until(...), but I am thinking that if you wanted to exit the wait_until(...) part early I am not sure how you would do that?
â code_fodder
Aug 13 at 7:47
6
6
You probably have a design issue and want to use a
std::future
instead. It has methods wait_for
and wait_until
.â Henri Menke
Aug 13 at 7:21
You probably have a design issue and want to use a
std::future
instead. It has methods wait_for
and wait_until
.â Henri Menke
Aug 13 at 7:21
How accurate does the timer need to be? Nothing wrong with using
sleep_for
in this way.â Bathsheba
Aug 13 at 7:21
How accurate does the timer need to be? Nothing wrong with using
sleep_for
in this way.â Bathsheba
Aug 13 at 7:21
2
2
sleep is bad for "synchronize" multiple thread together, your usage might be fine.
â Jarod42
Aug 13 at 7:21
sleep is bad for "synchronize" multiple thread together, your usage might be fine.
â Jarod42
Aug 13 at 7:21
1
1
in "standard c++11" this is about all you have. If you widen your net to include posix then you can build an io loop based on pselect et al. boost.asio is built (sort of) this way.
â Richard Hodges
Aug 13 at 7:22
in "standard c++11" this is about all you have. If you widen your net to include posix then you can build an io loop based on pselect et al. boost.asio is built (sort of) this way.
â Richard Hodges
Aug 13 at 7:22
@HenriMenke I like the idea of wait_until(...), but I am thinking that if you wanted to exit the wait_until(...) part early I am not sure how you would do that?
â code_fodder
Aug 13 at 7:47
@HenriMenke I like the idea of wait_until(...), but I am thinking that if you wanted to exit the wait_until(...) part early I am not sure how you would do that?
â code_fodder
Aug 13 at 7:47
 |Â
show 5 more comments
3 Answers
3
active
oldest
votes
up vote
33
down vote
accepted
C++11 provides us with std::condition_variable
. In your timer you can wait until your condition has been met:
// Somewhere else, e.g. in a header:
std::mutex mutex;
bool condition_to_be_metfalse;
std::condition_variable cv;
// In your timer:
// ...
std::unique_lock<std::mutex> lockmutex;
if(!cv.wait_for(lock, std::chrono::millisecondstimeout_ms, [this]return condition_to_be_met;))
std::cout << "timed out!" << std::endl;
You can find more information here: https://en.cppreference.com/w/cpp/thread/condition_variable
To signal that the condition has been met do this in another thread:
std::lock_guard<std::mutex> lockmutex; // Same instance as above!
condition_to_be_met = true;
cv.notify_one();
4
just a tiny comment. Adjustment ofcondition_to_be_met
is always guarded by a mutex, so it does not need to be atomic. Also, almost always release the lock before callingnotify_one()
. see docs: en.cppreference.com/w/cpp/thread/condition_variable/notify_one
â Richard Hodges
Aug 13 at 7:42
That is so cool! - I have used condition_variable quite a lot, but I just never really looked into wait_for() ... it does all the work for me!...nice : )) thanks
â code_fodder
Aug 13 at 7:47
@RichardHodges Good points, thank you, I edited my answer.
â Sebastian
Aug 13 at 7:47
std::unique_lock<std::mutex> lockmutex;
outside ofwait_for
? This means thatwait_for
will always work same way assleep
, sincecondition_to_be_met
can't be modified untilwait_for
is completed. Socondition_to_be_met
should be atomic, but no extra mutex should be used!
â Marek R
Aug 13 at 8:19
4
@MarekR That's not true, please read the reference onstd::condition_variable
andstd::unique_lock
. Basically,wait_for
locks and unlocks the mutex whenever it needs to. That's whywait_for
needs astd::unique_lock
to work and cannot take astd::lock_guard
.
â Sebastian
Aug 13 at 8:34
 |Â
show 3 more comments
up vote
5
down vote
While your code will "work", it is sub-optimal for the intended purpose as timer.
There exists std::this_thread::sleep_until
which, depending on the implementation, possibly only just calls sleep_for
after doing some math anyway, but which might use a proper timer, which is vastly superior in terms of precision and reliability.
Generally, sleeping is not the best, most reliable, and most accurate thing to do, but sometimes, if just waiting for some approximate time is what's intended, it can be "good enough".
In any case, repeatedly sleeping for small amounts as in your example is a bad idea. This will burn a lot of CPU on needlessly rescheduling and waking threads, and on some systems (Windows in particular, though Windows 10 isn't so bad in that respect any more) it may add a considerable amount of jitter and uncertainity. Note that different Windows versions round to the scheduler's granularity differently, so in addition to generally being not overly precise, you do not even have consistent behavior. Rounding is pretty much "who cares" for a single large wait, but it is a serious problem for a series of small waits.
Unless the ability to abort the timer prematurely is a necessity (but in that case, there are better ways of implementing that, too!), you should sleep exactly once, never more, for the full duration. For correctness you should then check that you indeed got the time you expected because some systems (POSIX, notably) may under-sleep.
Over-sleeping is a different problem if you need it right, because even if you check and detect that case correctly, once it has happened there's nothing you can do about it (time has already passed, and never comes back). But alas, that's just a fundamental weakness of sleeping, not much you can do. Luckily, most people can shrug this problem off, most of the time.
Ah, yes... that is exactly why I am doing multiple sleeps, incase the caller wants to stop the timer (in which case I was using an atomic bool variable within the loop - if it gets set to true is escapes the loop...). But as you say, sleeping many times is not so "clever", so I like thecond_var.wait_for(...)
idea, that seems to capture both cases. :)
â code_fodder
Aug 13 at 15:38
The "correct" way (or one correct way) of doing this would be to check an atomic flag prior to executing the to-do stuff once the timer fires, basically that's very much like using thescope_guard
idiom and callingdisarm()
if you want to cancel the timer (only just, normal implementations ofscope_guard
aren't threadsafe, they need not be). You only need to check once at the very end. Yes, if you cancel, you will effectively have a superfluous thread doing nothing, until it exits. Get over it. You don't spawn and cancel 5,000 times per program invocation, so who cares.
â Damon
Aug 13 at 16:10
mmm... I do see what you are saying. But it feels wrong to leave "active" timers kicking around just because you can't implement a decent way of ending them :o ... or is that just my OCD?!
â code_fodder
Aug 13 at 16:13
Well a thread that is sleeping does nothing. Once it wakes up, it checks one boolean, sees that it should exit, and exits. All you really lose is the address space reserved for the thread's stack. Unless you have a lot of threads, this doesn't matter. The next best thing would be to simply kill the threads. While they're sleeping, this is 100% harmless. Only problem is a) C++ doesn't support it, so you need to go low level, and b) what happens if you kill them while they're half through the critical section after waking up! Problem b) can be addressed cleanly under POSIX, but not Windows.
â Damon
Aug 13 at 16:42
yeah I did have a look at how to kill off threads - the only way I found was std::terminate (or is it std::thread::terminate), but that also terminates the entire application :o. So on more consideration I think your answer is a valid one... +1, but not the one I prefer because I like being neat :o ... even if its just in my head only!
â code_fodder
Aug 14 at 8:21
add a comment |Â
up vote
3
down vote
You could busy-wait checking the time in a loop, until it reaches the time you're waiting for. That's obviously horrible, so don't do it. Sleeping for 10ms is somewhat better, but definitely poor design. (@Damon's answer has some good info.)
There's nothing wrong with using functions with sleep
in their name if that's the most useful thing for your program to do right then.
The suggestion to avoid sleep
is probably recommending against the general pattern of sleeping for a short time, checking if there's anything to do, then sleeping again. Instead, block waiting for an event with no timeout, or a very long timeout. (e.g. a GUI should wait for a keypress / click by calling a blocking function, with a timeout set to wake it up when it's time to autosave or whatever future thing is coming up next. You normally don't need a separate thread just to sleep, but you might if there's nowhere sensible to insert checks for the current time.)
Letting the OS wake you up when it's finally time to do anything is much better. This avoids context switches and cache pollution slowing down other programs and wasting power while you're spinning on short sleeps.
If you know there's nothing to do for some time, just sleep for that long with a single sleep. AFAIK, multiple short sleeps won't improve the accuracy of the wake-up time on mainstream OSes like Windows, Linux, or OS X. You might avoid an instruction-cache if your code had been waking up frequently, but if that amount of delay is a real problem you probably need a real-time OS and a much more sophisticated approach to timing.
If anything, a thread that's been sleeping for a long time is more likely to wake up exactly when it requested, while a thread that was running recently and slept for only 10ms might run into scheduler timeslice issues. On Linux, threads that have been asleep for a while get a priority boost when they do wake up.
Using a function without sleep
in the name that blocks for 1 second is no better than using sleep
or this_thread::sleep_for
.
(Apparently you want another thread to be able to wake you up. This requirement is buried in the question, but yes a condition variable is a good portable way to do that.)
If you want to use pure ISO C++11, then std::this_thread::sleep_for
or std::this_thread::sleep_until
are your best bet. These are defined in standard header <thread>
.
sleep(3)
is a POSIX function (like nanosleep
), not part of ISO C++11. If that's not a problem for you, then feel free to use it if it's appropriate.
For portable high-precision OS-assisted sleep-for-an-interval, C++11 introducedstd::this_thread::sleep_for(const std::chrono::duration<Rep, Period> &sleep_duration)
(The cppreference page has a code example of using it.)
Blocks the execution of the current thread for at least the specified sleep_duration.
This function may block for longer than sleep_duration due to
scheduling or resource contention delays.
The standard recommends that a steady clock is used to measure the
duration. If an implementation uses a system clock instead, the wait
time may also be sensitive to clock adjustments.
To sleep until a clock reaches a specified time (possibly taking into account changes / corrections to the system time):
std::this_thread::sleep_until(const std::chrono::time_point<Clock,Duration>& sleep_time)
Blocks the execution of the current thread until specified
sleep_time
has been reached.
The clock tied to
sleep_time
is used, which means that adjustments of
the clock are taken into account. Thus, the duration of the block
might, but might not, be less or more thansleep_time - Clock::now()
at the time of the call, depending on the direction of the adjustment.
The function also may block for longer than until aftersleep_time
has
been reached due to scheduling or resource contention delays.
Notice that sleep_for
is meant to be unaffected by changes to the system clock, so it sleeps for that much real time.
But sleep_until
is supposed to let you wake up when the system clock reaches a given time, even if it did that by being adjusted (NTP or manual setting), if used with a clock other than steady_clock
.
Sleep gotchas: late / early wakeup
The caveats about possibly sleeping too long also apply to sleep
and nanosleep
, or any other OS-specific sleep or timeout (including the condition-variable approach in @Sebastian's answer), of course. It's unavoidable; a realtime OS can give you upper bounds on that extra delay, though.
You're already doing something like this with your 10ms sleeps:
Always assume that sleep
or whatever other function woke up late, and check the current time instead of using dead-reckoning in any case where that matters.
You can't build a reliable clock out of repeated sleep
.
e.g. don't build a count-down timer that sleeps for 1 second, decrements and displays a counter, then sleeps for another second. Unless it's just a toy and you don't care much about accuracy.
Some sleep functions such as POSIX sleep(3)
can also wake up early on a signal. If waking too early is a correctness problem, check the time and if necessary go back to sleep for the calculated interval. (Or use sleep_until
)
1
Peter - I might be being slow here... but I don't quite get what you are getting at. I think I am doing what you are suggesting already? I am usingstd::this_thread::sleep_for(...)
already and my loop (buried in my stopwatch class) is taking a time time-stamp such that after each interval it checks the actual time taken (and not just a series of sleep_for()'s added together. Is that what you mean?
â code_fodder
Aug 13 at 15:34
@code_fodder: I read the title and thought you were asking aboutsleep
. I only later realized you were already asking aboutthis_thread::sleep_for
but didn't have any good ideas for rewriting my answer. The requirement that another thread be able to wake you was totally buried in your question, and not obvious from the code. A conditional variable is a very good portable option there, otherwise do one sleep for the full duration. Like Damon says, multiple short sleeps aren't efficient. Not as bad as busy-waiting, but AFAIK short sleeps don't improve precision of the wake time.
â Peter Cordes
Aug 14 at 0:17
1
@PeterCordes Actaully I don't think I even added the requirement to wakeup... I probably should!.. good spot. But at least from your answer I can see that I started along the right direction : )
â code_fodder
Aug 14 at 8:11
@isanae: I updated it to maybe make more sense as an answer to this question. If you do just want to sleep, then avoiding functions withsleep
in the name is not useful if you're just going to use some other function in a way that makes it block for a fixed interval. @Damon's answer is better than mine, though.
â Peter Cordes
Aug 14 at 8:31
I retracted my downvote 8 hours ago after your edit. I haven't upvoted it because I don't think this is a good quality answer: it's confused, it has many unrelated sections and it is unclear what or where the actual answer is. I would suggest trimming most of it and cleaning up the layout.
â isanae
Aug 14 at 8:36
 |Â
show 3 more comments
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
33
down vote
accepted
C++11 provides us with std::condition_variable
. In your timer you can wait until your condition has been met:
// Somewhere else, e.g. in a header:
std::mutex mutex;
bool condition_to_be_metfalse;
std::condition_variable cv;
// In your timer:
// ...
std::unique_lock<std::mutex> lockmutex;
if(!cv.wait_for(lock, std::chrono::millisecondstimeout_ms, [this]return condition_to_be_met;))
std::cout << "timed out!" << std::endl;
You can find more information here: https://en.cppreference.com/w/cpp/thread/condition_variable
To signal that the condition has been met do this in another thread:
std::lock_guard<std::mutex> lockmutex; // Same instance as above!
condition_to_be_met = true;
cv.notify_one();
4
just a tiny comment. Adjustment ofcondition_to_be_met
is always guarded by a mutex, so it does not need to be atomic. Also, almost always release the lock before callingnotify_one()
. see docs: en.cppreference.com/w/cpp/thread/condition_variable/notify_one
â Richard Hodges
Aug 13 at 7:42
That is so cool! - I have used condition_variable quite a lot, but I just never really looked into wait_for() ... it does all the work for me!...nice : )) thanks
â code_fodder
Aug 13 at 7:47
@RichardHodges Good points, thank you, I edited my answer.
â Sebastian
Aug 13 at 7:47
std::unique_lock<std::mutex> lockmutex;
outside ofwait_for
? This means thatwait_for
will always work same way assleep
, sincecondition_to_be_met
can't be modified untilwait_for
is completed. Socondition_to_be_met
should be atomic, but no extra mutex should be used!
â Marek R
Aug 13 at 8:19
4
@MarekR That's not true, please read the reference onstd::condition_variable
andstd::unique_lock
. Basically,wait_for
locks and unlocks the mutex whenever it needs to. That's whywait_for
needs astd::unique_lock
to work and cannot take astd::lock_guard
.
â Sebastian
Aug 13 at 8:34
 |Â
show 3 more comments
up vote
33
down vote
accepted
C++11 provides us with std::condition_variable
. In your timer you can wait until your condition has been met:
// Somewhere else, e.g. in a header:
std::mutex mutex;
bool condition_to_be_metfalse;
std::condition_variable cv;
// In your timer:
// ...
std::unique_lock<std::mutex> lockmutex;
if(!cv.wait_for(lock, std::chrono::millisecondstimeout_ms, [this]return condition_to_be_met;))
std::cout << "timed out!" << std::endl;
You can find more information here: https://en.cppreference.com/w/cpp/thread/condition_variable
To signal that the condition has been met do this in another thread:
std::lock_guard<std::mutex> lockmutex; // Same instance as above!
condition_to_be_met = true;
cv.notify_one();
4
just a tiny comment. Adjustment ofcondition_to_be_met
is always guarded by a mutex, so it does not need to be atomic. Also, almost always release the lock before callingnotify_one()
. see docs: en.cppreference.com/w/cpp/thread/condition_variable/notify_one
â Richard Hodges
Aug 13 at 7:42
That is so cool! - I have used condition_variable quite a lot, but I just never really looked into wait_for() ... it does all the work for me!...nice : )) thanks
â code_fodder
Aug 13 at 7:47
@RichardHodges Good points, thank you, I edited my answer.
â Sebastian
Aug 13 at 7:47
std::unique_lock<std::mutex> lockmutex;
outside ofwait_for
? This means thatwait_for
will always work same way assleep
, sincecondition_to_be_met
can't be modified untilwait_for
is completed. Socondition_to_be_met
should be atomic, but no extra mutex should be used!
â Marek R
Aug 13 at 8:19
4
@MarekR That's not true, please read the reference onstd::condition_variable
andstd::unique_lock
. Basically,wait_for
locks and unlocks the mutex whenever it needs to. That's whywait_for
needs astd::unique_lock
to work and cannot take astd::lock_guard
.
â Sebastian
Aug 13 at 8:34
 |Â
show 3 more comments
up vote
33
down vote
accepted
up vote
33
down vote
accepted
C++11 provides us with std::condition_variable
. In your timer you can wait until your condition has been met:
// Somewhere else, e.g. in a header:
std::mutex mutex;
bool condition_to_be_metfalse;
std::condition_variable cv;
// In your timer:
// ...
std::unique_lock<std::mutex> lockmutex;
if(!cv.wait_for(lock, std::chrono::millisecondstimeout_ms, [this]return condition_to_be_met;))
std::cout << "timed out!" << std::endl;
You can find more information here: https://en.cppreference.com/w/cpp/thread/condition_variable
To signal that the condition has been met do this in another thread:
std::lock_guard<std::mutex> lockmutex; // Same instance as above!
condition_to_be_met = true;
cv.notify_one();
C++11 provides us with std::condition_variable
. In your timer you can wait until your condition has been met:
// Somewhere else, e.g. in a header:
std::mutex mutex;
bool condition_to_be_metfalse;
std::condition_variable cv;
// In your timer:
// ...
std::unique_lock<std::mutex> lockmutex;
if(!cv.wait_for(lock, std::chrono::millisecondstimeout_ms, [this]return condition_to_be_met;))
std::cout << "timed out!" << std::endl;
You can find more information here: https://en.cppreference.com/w/cpp/thread/condition_variable
To signal that the condition has been met do this in another thread:
std::lock_guard<std::mutex> lockmutex; // Same instance as above!
condition_to_be_met = true;
cv.notify_one();
edited Aug 13 at 15:53
answered Aug 13 at 7:22
Sebastian
41649
41649
4
just a tiny comment. Adjustment ofcondition_to_be_met
is always guarded by a mutex, so it does not need to be atomic. Also, almost always release the lock before callingnotify_one()
. see docs: en.cppreference.com/w/cpp/thread/condition_variable/notify_one
â Richard Hodges
Aug 13 at 7:42
That is so cool! - I have used condition_variable quite a lot, but I just never really looked into wait_for() ... it does all the work for me!...nice : )) thanks
â code_fodder
Aug 13 at 7:47
@RichardHodges Good points, thank you, I edited my answer.
â Sebastian
Aug 13 at 7:47
std::unique_lock<std::mutex> lockmutex;
outside ofwait_for
? This means thatwait_for
will always work same way assleep
, sincecondition_to_be_met
can't be modified untilwait_for
is completed. Socondition_to_be_met
should be atomic, but no extra mutex should be used!
â Marek R
Aug 13 at 8:19
4
@MarekR That's not true, please read the reference onstd::condition_variable
andstd::unique_lock
. Basically,wait_for
locks and unlocks the mutex whenever it needs to. That's whywait_for
needs astd::unique_lock
to work and cannot take astd::lock_guard
.
â Sebastian
Aug 13 at 8:34
 |Â
show 3 more comments
4
just a tiny comment. Adjustment ofcondition_to_be_met
is always guarded by a mutex, so it does not need to be atomic. Also, almost always release the lock before callingnotify_one()
. see docs: en.cppreference.com/w/cpp/thread/condition_variable/notify_one
â Richard Hodges
Aug 13 at 7:42
That is so cool! - I have used condition_variable quite a lot, but I just never really looked into wait_for() ... it does all the work for me!...nice : )) thanks
â code_fodder
Aug 13 at 7:47
@RichardHodges Good points, thank you, I edited my answer.
â Sebastian
Aug 13 at 7:47
std::unique_lock<std::mutex> lockmutex;
outside ofwait_for
? This means thatwait_for
will always work same way assleep
, sincecondition_to_be_met
can't be modified untilwait_for
is completed. Socondition_to_be_met
should be atomic, but no extra mutex should be used!
â Marek R
Aug 13 at 8:19
4
@MarekR That's not true, please read the reference onstd::condition_variable
andstd::unique_lock
. Basically,wait_for
locks and unlocks the mutex whenever it needs to. That's whywait_for
needs astd::unique_lock
to work and cannot take astd::lock_guard
.
â Sebastian
Aug 13 at 8:34
4
4
just a tiny comment. Adjustment of
condition_to_be_met
is always guarded by a mutex, so it does not need to be atomic. Also, almost always release the lock before calling notify_one()
. see docs: en.cppreference.com/w/cpp/thread/condition_variable/notify_oneâ Richard Hodges
Aug 13 at 7:42
just a tiny comment. Adjustment of
condition_to_be_met
is always guarded by a mutex, so it does not need to be atomic. Also, almost always release the lock before calling notify_one()
. see docs: en.cppreference.com/w/cpp/thread/condition_variable/notify_oneâ Richard Hodges
Aug 13 at 7:42
That is so cool! - I have used condition_variable quite a lot, but I just never really looked into wait_for() ... it does all the work for me!...nice : )) thanks
â code_fodder
Aug 13 at 7:47
That is so cool! - I have used condition_variable quite a lot, but I just never really looked into wait_for() ... it does all the work for me!...nice : )) thanks
â code_fodder
Aug 13 at 7:47
@RichardHodges Good points, thank you, I edited my answer.
â Sebastian
Aug 13 at 7:47
@RichardHodges Good points, thank you, I edited my answer.
â Sebastian
Aug 13 at 7:47
std::unique_lock<std::mutex> lockmutex;
outside of wait_for
? This means that wait_for
will always work same way as sleep
, since condition_to_be_met
can't be modified until wait_for
is completed. So condition_to_be_met
should be atomic, but no extra mutex should be used!â Marek R
Aug 13 at 8:19
std::unique_lock<std::mutex> lockmutex;
outside of wait_for
? This means that wait_for
will always work same way as sleep
, since condition_to_be_met
can't be modified until wait_for
is completed. So condition_to_be_met
should be atomic, but no extra mutex should be used!â Marek R
Aug 13 at 8:19
4
4
@MarekR That's not true, please read the reference on
std::condition_variable
and std::unique_lock
. Basically, wait_for
locks and unlocks the mutex whenever it needs to. That's why wait_for
needs a std::unique_lock
to work and cannot take a std::lock_guard
.â Sebastian
Aug 13 at 8:34
@MarekR That's not true, please read the reference on
std::condition_variable
and std::unique_lock
. Basically, wait_for
locks and unlocks the mutex whenever it needs to. That's why wait_for
needs a std::unique_lock
to work and cannot take a std::lock_guard
.â Sebastian
Aug 13 at 8:34
 |Â
show 3 more comments
up vote
5
down vote
While your code will "work", it is sub-optimal for the intended purpose as timer.
There exists std::this_thread::sleep_until
which, depending on the implementation, possibly only just calls sleep_for
after doing some math anyway, but which might use a proper timer, which is vastly superior in terms of precision and reliability.
Generally, sleeping is not the best, most reliable, and most accurate thing to do, but sometimes, if just waiting for some approximate time is what's intended, it can be "good enough".
In any case, repeatedly sleeping for small amounts as in your example is a bad idea. This will burn a lot of CPU on needlessly rescheduling and waking threads, and on some systems (Windows in particular, though Windows 10 isn't so bad in that respect any more) it may add a considerable amount of jitter and uncertainity. Note that different Windows versions round to the scheduler's granularity differently, so in addition to generally being not overly precise, you do not even have consistent behavior. Rounding is pretty much "who cares" for a single large wait, but it is a serious problem for a series of small waits.
Unless the ability to abort the timer prematurely is a necessity (but in that case, there are better ways of implementing that, too!), you should sleep exactly once, never more, for the full duration. For correctness you should then check that you indeed got the time you expected because some systems (POSIX, notably) may under-sleep.
Over-sleeping is a different problem if you need it right, because even if you check and detect that case correctly, once it has happened there's nothing you can do about it (time has already passed, and never comes back). But alas, that's just a fundamental weakness of sleeping, not much you can do. Luckily, most people can shrug this problem off, most of the time.
Ah, yes... that is exactly why I am doing multiple sleeps, incase the caller wants to stop the timer (in which case I was using an atomic bool variable within the loop - if it gets set to true is escapes the loop...). But as you say, sleeping many times is not so "clever", so I like thecond_var.wait_for(...)
idea, that seems to capture both cases. :)
â code_fodder
Aug 13 at 15:38
The "correct" way (or one correct way) of doing this would be to check an atomic flag prior to executing the to-do stuff once the timer fires, basically that's very much like using thescope_guard
idiom and callingdisarm()
if you want to cancel the timer (only just, normal implementations ofscope_guard
aren't threadsafe, they need not be). You only need to check once at the very end. Yes, if you cancel, you will effectively have a superfluous thread doing nothing, until it exits. Get over it. You don't spawn and cancel 5,000 times per program invocation, so who cares.
â Damon
Aug 13 at 16:10
mmm... I do see what you are saying. But it feels wrong to leave "active" timers kicking around just because you can't implement a decent way of ending them :o ... or is that just my OCD?!
â code_fodder
Aug 13 at 16:13
Well a thread that is sleeping does nothing. Once it wakes up, it checks one boolean, sees that it should exit, and exits. All you really lose is the address space reserved for the thread's stack. Unless you have a lot of threads, this doesn't matter. The next best thing would be to simply kill the threads. While they're sleeping, this is 100% harmless. Only problem is a) C++ doesn't support it, so you need to go low level, and b) what happens if you kill them while they're half through the critical section after waking up! Problem b) can be addressed cleanly under POSIX, but not Windows.
â Damon
Aug 13 at 16:42
yeah I did have a look at how to kill off threads - the only way I found was std::terminate (or is it std::thread::terminate), but that also terminates the entire application :o. So on more consideration I think your answer is a valid one... +1, but not the one I prefer because I like being neat :o ... even if its just in my head only!
â code_fodder
Aug 14 at 8:21
add a comment |Â
up vote
5
down vote
While your code will "work", it is sub-optimal for the intended purpose as timer.
There exists std::this_thread::sleep_until
which, depending on the implementation, possibly only just calls sleep_for
after doing some math anyway, but which might use a proper timer, which is vastly superior in terms of precision and reliability.
Generally, sleeping is not the best, most reliable, and most accurate thing to do, but sometimes, if just waiting for some approximate time is what's intended, it can be "good enough".
In any case, repeatedly sleeping for small amounts as in your example is a bad idea. This will burn a lot of CPU on needlessly rescheduling and waking threads, and on some systems (Windows in particular, though Windows 10 isn't so bad in that respect any more) it may add a considerable amount of jitter and uncertainity. Note that different Windows versions round to the scheduler's granularity differently, so in addition to generally being not overly precise, you do not even have consistent behavior. Rounding is pretty much "who cares" for a single large wait, but it is a serious problem for a series of small waits.
Unless the ability to abort the timer prematurely is a necessity (but in that case, there are better ways of implementing that, too!), you should sleep exactly once, never more, for the full duration. For correctness you should then check that you indeed got the time you expected because some systems (POSIX, notably) may under-sleep.
Over-sleeping is a different problem if you need it right, because even if you check and detect that case correctly, once it has happened there's nothing you can do about it (time has already passed, and never comes back). But alas, that's just a fundamental weakness of sleeping, not much you can do. Luckily, most people can shrug this problem off, most of the time.
Ah, yes... that is exactly why I am doing multiple sleeps, incase the caller wants to stop the timer (in which case I was using an atomic bool variable within the loop - if it gets set to true is escapes the loop...). But as you say, sleeping many times is not so "clever", so I like thecond_var.wait_for(...)
idea, that seems to capture both cases. :)
â code_fodder
Aug 13 at 15:38
The "correct" way (or one correct way) of doing this would be to check an atomic flag prior to executing the to-do stuff once the timer fires, basically that's very much like using thescope_guard
idiom and callingdisarm()
if you want to cancel the timer (only just, normal implementations ofscope_guard
aren't threadsafe, they need not be). You only need to check once at the very end. Yes, if you cancel, you will effectively have a superfluous thread doing nothing, until it exits. Get over it. You don't spawn and cancel 5,000 times per program invocation, so who cares.
â Damon
Aug 13 at 16:10
mmm... I do see what you are saying. But it feels wrong to leave "active" timers kicking around just because you can't implement a decent way of ending them :o ... or is that just my OCD?!
â code_fodder
Aug 13 at 16:13
Well a thread that is sleeping does nothing. Once it wakes up, it checks one boolean, sees that it should exit, and exits. All you really lose is the address space reserved for the thread's stack. Unless you have a lot of threads, this doesn't matter. The next best thing would be to simply kill the threads. While they're sleeping, this is 100% harmless. Only problem is a) C++ doesn't support it, so you need to go low level, and b) what happens if you kill them while they're half through the critical section after waking up! Problem b) can be addressed cleanly under POSIX, but not Windows.
â Damon
Aug 13 at 16:42
yeah I did have a look at how to kill off threads - the only way I found was std::terminate (or is it std::thread::terminate), but that also terminates the entire application :o. So on more consideration I think your answer is a valid one... +1, but not the one I prefer because I like being neat :o ... even if its just in my head only!
â code_fodder
Aug 14 at 8:21
add a comment |Â
up vote
5
down vote
up vote
5
down vote
While your code will "work", it is sub-optimal for the intended purpose as timer.
There exists std::this_thread::sleep_until
which, depending on the implementation, possibly only just calls sleep_for
after doing some math anyway, but which might use a proper timer, which is vastly superior in terms of precision and reliability.
Generally, sleeping is not the best, most reliable, and most accurate thing to do, but sometimes, if just waiting for some approximate time is what's intended, it can be "good enough".
In any case, repeatedly sleeping for small amounts as in your example is a bad idea. This will burn a lot of CPU on needlessly rescheduling and waking threads, and on some systems (Windows in particular, though Windows 10 isn't so bad in that respect any more) it may add a considerable amount of jitter and uncertainity. Note that different Windows versions round to the scheduler's granularity differently, so in addition to generally being not overly precise, you do not even have consistent behavior. Rounding is pretty much "who cares" for a single large wait, but it is a serious problem for a series of small waits.
Unless the ability to abort the timer prematurely is a necessity (but in that case, there are better ways of implementing that, too!), you should sleep exactly once, never more, for the full duration. For correctness you should then check that you indeed got the time you expected because some systems (POSIX, notably) may under-sleep.
Over-sleeping is a different problem if you need it right, because even if you check and detect that case correctly, once it has happened there's nothing you can do about it (time has already passed, and never comes back). But alas, that's just a fundamental weakness of sleeping, not much you can do. Luckily, most people can shrug this problem off, most of the time.
While your code will "work", it is sub-optimal for the intended purpose as timer.
There exists std::this_thread::sleep_until
which, depending on the implementation, possibly only just calls sleep_for
after doing some math anyway, but which might use a proper timer, which is vastly superior in terms of precision and reliability.
Generally, sleeping is not the best, most reliable, and most accurate thing to do, but sometimes, if just waiting for some approximate time is what's intended, it can be "good enough".
In any case, repeatedly sleeping for small amounts as in your example is a bad idea. This will burn a lot of CPU on needlessly rescheduling and waking threads, and on some systems (Windows in particular, though Windows 10 isn't so bad in that respect any more) it may add a considerable amount of jitter and uncertainity. Note that different Windows versions round to the scheduler's granularity differently, so in addition to generally being not overly precise, you do not even have consistent behavior. Rounding is pretty much "who cares" for a single large wait, but it is a serious problem for a series of small waits.
Unless the ability to abort the timer prematurely is a necessity (but in that case, there are better ways of implementing that, too!), you should sleep exactly once, never more, for the full duration. For correctness you should then check that you indeed got the time you expected because some systems (POSIX, notably) may under-sleep.
Over-sleeping is a different problem if you need it right, because even if you check and detect that case correctly, once it has happened there's nothing you can do about it (time has already passed, and never comes back). But alas, that's just a fundamental weakness of sleeping, not much you can do. Luckily, most people can shrug this problem off, most of the time.
answered Aug 13 at 14:14
Damon
49.3k1493151
49.3k1493151
Ah, yes... that is exactly why I am doing multiple sleeps, incase the caller wants to stop the timer (in which case I was using an atomic bool variable within the loop - if it gets set to true is escapes the loop...). But as you say, sleeping many times is not so "clever", so I like thecond_var.wait_for(...)
idea, that seems to capture both cases. :)
â code_fodder
Aug 13 at 15:38
The "correct" way (or one correct way) of doing this would be to check an atomic flag prior to executing the to-do stuff once the timer fires, basically that's very much like using thescope_guard
idiom and callingdisarm()
if you want to cancel the timer (only just, normal implementations ofscope_guard
aren't threadsafe, they need not be). You only need to check once at the very end. Yes, if you cancel, you will effectively have a superfluous thread doing nothing, until it exits. Get over it. You don't spawn and cancel 5,000 times per program invocation, so who cares.
â Damon
Aug 13 at 16:10
mmm... I do see what you are saying. But it feels wrong to leave "active" timers kicking around just because you can't implement a decent way of ending them :o ... or is that just my OCD?!
â code_fodder
Aug 13 at 16:13
Well a thread that is sleeping does nothing. Once it wakes up, it checks one boolean, sees that it should exit, and exits. All you really lose is the address space reserved for the thread's stack. Unless you have a lot of threads, this doesn't matter. The next best thing would be to simply kill the threads. While they're sleeping, this is 100% harmless. Only problem is a) C++ doesn't support it, so you need to go low level, and b) what happens if you kill them while they're half through the critical section after waking up! Problem b) can be addressed cleanly under POSIX, but not Windows.
â Damon
Aug 13 at 16:42
yeah I did have a look at how to kill off threads - the only way I found was std::terminate (or is it std::thread::terminate), but that also terminates the entire application :o. So on more consideration I think your answer is a valid one... +1, but not the one I prefer because I like being neat :o ... even if its just in my head only!
â code_fodder
Aug 14 at 8:21
add a comment |Â
Ah, yes... that is exactly why I am doing multiple sleeps, incase the caller wants to stop the timer (in which case I was using an atomic bool variable within the loop - if it gets set to true is escapes the loop...). But as you say, sleeping many times is not so "clever", so I like thecond_var.wait_for(...)
idea, that seems to capture both cases. :)
â code_fodder
Aug 13 at 15:38
The "correct" way (or one correct way) of doing this would be to check an atomic flag prior to executing the to-do stuff once the timer fires, basically that's very much like using thescope_guard
idiom and callingdisarm()
if you want to cancel the timer (only just, normal implementations ofscope_guard
aren't threadsafe, they need not be). You only need to check once at the very end. Yes, if you cancel, you will effectively have a superfluous thread doing nothing, until it exits. Get over it. You don't spawn and cancel 5,000 times per program invocation, so who cares.
â Damon
Aug 13 at 16:10
mmm... I do see what you are saying. But it feels wrong to leave "active" timers kicking around just because you can't implement a decent way of ending them :o ... or is that just my OCD?!
â code_fodder
Aug 13 at 16:13
Well a thread that is sleeping does nothing. Once it wakes up, it checks one boolean, sees that it should exit, and exits. All you really lose is the address space reserved for the thread's stack. Unless you have a lot of threads, this doesn't matter. The next best thing would be to simply kill the threads. While they're sleeping, this is 100% harmless. Only problem is a) C++ doesn't support it, so you need to go low level, and b) what happens if you kill them while they're half through the critical section after waking up! Problem b) can be addressed cleanly under POSIX, but not Windows.
â Damon
Aug 13 at 16:42
yeah I did have a look at how to kill off threads - the only way I found was std::terminate (or is it std::thread::terminate), but that also terminates the entire application :o. So on more consideration I think your answer is a valid one... +1, but not the one I prefer because I like being neat :o ... even if its just in my head only!
â code_fodder
Aug 14 at 8:21
Ah, yes... that is exactly why I am doing multiple sleeps, incase the caller wants to stop the timer (in which case I was using an atomic bool variable within the loop - if it gets set to true is escapes the loop...). But as you say, sleeping many times is not so "clever", so I like the
cond_var.wait_for(...)
idea, that seems to capture both cases. :)â code_fodder
Aug 13 at 15:38
Ah, yes... that is exactly why I am doing multiple sleeps, incase the caller wants to stop the timer (in which case I was using an atomic bool variable within the loop - if it gets set to true is escapes the loop...). But as you say, sleeping many times is not so "clever", so I like the
cond_var.wait_for(...)
idea, that seems to capture both cases. :)â code_fodder
Aug 13 at 15:38
The "correct" way (or one correct way) of doing this would be to check an atomic flag prior to executing the to-do stuff once the timer fires, basically that's very much like using the
scope_guard
idiom and calling disarm()
if you want to cancel the timer (only just, normal implementations of scope_guard
aren't threadsafe, they need not be). You only need to check once at the very end. Yes, if you cancel, you will effectively have a superfluous thread doing nothing, until it exits. Get over it. You don't spawn and cancel 5,000 times per program invocation, so who cares.â Damon
Aug 13 at 16:10
The "correct" way (or one correct way) of doing this would be to check an atomic flag prior to executing the to-do stuff once the timer fires, basically that's very much like using the
scope_guard
idiom and calling disarm()
if you want to cancel the timer (only just, normal implementations of scope_guard
aren't threadsafe, they need not be). You only need to check once at the very end. Yes, if you cancel, you will effectively have a superfluous thread doing nothing, until it exits. Get over it. You don't spawn and cancel 5,000 times per program invocation, so who cares.â Damon
Aug 13 at 16:10
mmm... I do see what you are saying. But it feels wrong to leave "active" timers kicking around just because you can't implement a decent way of ending them :o ... or is that just my OCD?!
â code_fodder
Aug 13 at 16:13
mmm... I do see what you are saying. But it feels wrong to leave "active" timers kicking around just because you can't implement a decent way of ending them :o ... or is that just my OCD?!
â code_fodder
Aug 13 at 16:13
Well a thread that is sleeping does nothing. Once it wakes up, it checks one boolean, sees that it should exit, and exits. All you really lose is the address space reserved for the thread's stack. Unless you have a lot of threads, this doesn't matter. The next best thing would be to simply kill the threads. While they're sleeping, this is 100% harmless. Only problem is a) C++ doesn't support it, so you need to go low level, and b) what happens if you kill them while they're half through the critical section after waking up! Problem b) can be addressed cleanly under POSIX, but not Windows.
â Damon
Aug 13 at 16:42
Well a thread that is sleeping does nothing. Once it wakes up, it checks one boolean, sees that it should exit, and exits. All you really lose is the address space reserved for the thread's stack. Unless you have a lot of threads, this doesn't matter. The next best thing would be to simply kill the threads. While they're sleeping, this is 100% harmless. Only problem is a) C++ doesn't support it, so you need to go low level, and b) what happens if you kill them while they're half through the critical section after waking up! Problem b) can be addressed cleanly under POSIX, but not Windows.
â Damon
Aug 13 at 16:42
yeah I did have a look at how to kill off threads - the only way I found was std::terminate (or is it std::thread::terminate), but that also terminates the entire application :o. So on more consideration I think your answer is a valid one... +1, but not the one I prefer because I like being neat :o ... even if its just in my head only!
â code_fodder
Aug 14 at 8:21
yeah I did have a look at how to kill off threads - the only way I found was std::terminate (or is it std::thread::terminate), but that also terminates the entire application :o. So on more consideration I think your answer is a valid one... +1, but not the one I prefer because I like being neat :o ... even if its just in my head only!
â code_fodder
Aug 14 at 8:21
add a comment |Â
up vote
3
down vote
You could busy-wait checking the time in a loop, until it reaches the time you're waiting for. That's obviously horrible, so don't do it. Sleeping for 10ms is somewhat better, but definitely poor design. (@Damon's answer has some good info.)
There's nothing wrong with using functions with sleep
in their name if that's the most useful thing for your program to do right then.
The suggestion to avoid sleep
is probably recommending against the general pattern of sleeping for a short time, checking if there's anything to do, then sleeping again. Instead, block waiting for an event with no timeout, or a very long timeout. (e.g. a GUI should wait for a keypress / click by calling a blocking function, with a timeout set to wake it up when it's time to autosave or whatever future thing is coming up next. You normally don't need a separate thread just to sleep, but you might if there's nowhere sensible to insert checks for the current time.)
Letting the OS wake you up when it's finally time to do anything is much better. This avoids context switches and cache pollution slowing down other programs and wasting power while you're spinning on short sleeps.
If you know there's nothing to do for some time, just sleep for that long with a single sleep. AFAIK, multiple short sleeps won't improve the accuracy of the wake-up time on mainstream OSes like Windows, Linux, or OS X. You might avoid an instruction-cache if your code had been waking up frequently, but if that amount of delay is a real problem you probably need a real-time OS and a much more sophisticated approach to timing.
If anything, a thread that's been sleeping for a long time is more likely to wake up exactly when it requested, while a thread that was running recently and slept for only 10ms might run into scheduler timeslice issues. On Linux, threads that have been asleep for a while get a priority boost when they do wake up.
Using a function without sleep
in the name that blocks for 1 second is no better than using sleep
or this_thread::sleep_for
.
(Apparently you want another thread to be able to wake you up. This requirement is buried in the question, but yes a condition variable is a good portable way to do that.)
If you want to use pure ISO C++11, then std::this_thread::sleep_for
or std::this_thread::sleep_until
are your best bet. These are defined in standard header <thread>
.
sleep(3)
is a POSIX function (like nanosleep
), not part of ISO C++11. If that's not a problem for you, then feel free to use it if it's appropriate.
For portable high-precision OS-assisted sleep-for-an-interval, C++11 introducedstd::this_thread::sleep_for(const std::chrono::duration<Rep, Period> &sleep_duration)
(The cppreference page has a code example of using it.)
Blocks the execution of the current thread for at least the specified sleep_duration.
This function may block for longer than sleep_duration due to
scheduling or resource contention delays.
The standard recommends that a steady clock is used to measure the
duration. If an implementation uses a system clock instead, the wait
time may also be sensitive to clock adjustments.
To sleep until a clock reaches a specified time (possibly taking into account changes / corrections to the system time):
std::this_thread::sleep_until(const std::chrono::time_point<Clock,Duration>& sleep_time)
Blocks the execution of the current thread until specified
sleep_time
has been reached.
The clock tied to
sleep_time
is used, which means that adjustments of
the clock are taken into account. Thus, the duration of the block
might, but might not, be less or more thansleep_time - Clock::now()
at the time of the call, depending on the direction of the adjustment.
The function also may block for longer than until aftersleep_time
has
been reached due to scheduling or resource contention delays.
Notice that sleep_for
is meant to be unaffected by changes to the system clock, so it sleeps for that much real time.
But sleep_until
is supposed to let you wake up when the system clock reaches a given time, even if it did that by being adjusted (NTP or manual setting), if used with a clock other than steady_clock
.
Sleep gotchas: late / early wakeup
The caveats about possibly sleeping too long also apply to sleep
and nanosleep
, or any other OS-specific sleep or timeout (including the condition-variable approach in @Sebastian's answer), of course. It's unavoidable; a realtime OS can give you upper bounds on that extra delay, though.
You're already doing something like this with your 10ms sleeps:
Always assume that sleep
or whatever other function woke up late, and check the current time instead of using dead-reckoning in any case where that matters.
You can't build a reliable clock out of repeated sleep
.
e.g. don't build a count-down timer that sleeps for 1 second, decrements and displays a counter, then sleeps for another second. Unless it's just a toy and you don't care much about accuracy.
Some sleep functions such as POSIX sleep(3)
can also wake up early on a signal. If waking too early is a correctness problem, check the time and if necessary go back to sleep for the calculated interval. (Or use sleep_until
)
1
Peter - I might be being slow here... but I don't quite get what you are getting at. I think I am doing what you are suggesting already? I am usingstd::this_thread::sleep_for(...)
already and my loop (buried in my stopwatch class) is taking a time time-stamp such that after each interval it checks the actual time taken (and not just a series of sleep_for()'s added together. Is that what you mean?
â code_fodder
Aug 13 at 15:34
@code_fodder: I read the title and thought you were asking aboutsleep
. I only later realized you were already asking aboutthis_thread::sleep_for
but didn't have any good ideas for rewriting my answer. The requirement that another thread be able to wake you was totally buried in your question, and not obvious from the code. A conditional variable is a very good portable option there, otherwise do one sleep for the full duration. Like Damon says, multiple short sleeps aren't efficient. Not as bad as busy-waiting, but AFAIK short sleeps don't improve precision of the wake time.
â Peter Cordes
Aug 14 at 0:17
1
@PeterCordes Actaully I don't think I even added the requirement to wakeup... I probably should!.. good spot. But at least from your answer I can see that I started along the right direction : )
â code_fodder
Aug 14 at 8:11
@isanae: I updated it to maybe make more sense as an answer to this question. If you do just want to sleep, then avoiding functions withsleep
in the name is not useful if you're just going to use some other function in a way that makes it block for a fixed interval. @Damon's answer is better than mine, though.
â Peter Cordes
Aug 14 at 8:31
I retracted my downvote 8 hours ago after your edit. I haven't upvoted it because I don't think this is a good quality answer: it's confused, it has many unrelated sections and it is unclear what or where the actual answer is. I would suggest trimming most of it and cleaning up the layout.
â isanae
Aug 14 at 8:36
 |Â
show 3 more comments
up vote
3
down vote
You could busy-wait checking the time in a loop, until it reaches the time you're waiting for. That's obviously horrible, so don't do it. Sleeping for 10ms is somewhat better, but definitely poor design. (@Damon's answer has some good info.)
There's nothing wrong with using functions with sleep
in their name if that's the most useful thing for your program to do right then.
The suggestion to avoid sleep
is probably recommending against the general pattern of sleeping for a short time, checking if there's anything to do, then sleeping again. Instead, block waiting for an event with no timeout, or a very long timeout. (e.g. a GUI should wait for a keypress / click by calling a blocking function, with a timeout set to wake it up when it's time to autosave or whatever future thing is coming up next. You normally don't need a separate thread just to sleep, but you might if there's nowhere sensible to insert checks for the current time.)
Letting the OS wake you up when it's finally time to do anything is much better. This avoids context switches and cache pollution slowing down other programs and wasting power while you're spinning on short sleeps.
If you know there's nothing to do for some time, just sleep for that long with a single sleep. AFAIK, multiple short sleeps won't improve the accuracy of the wake-up time on mainstream OSes like Windows, Linux, or OS X. You might avoid an instruction-cache if your code had been waking up frequently, but if that amount of delay is a real problem you probably need a real-time OS and a much more sophisticated approach to timing.
If anything, a thread that's been sleeping for a long time is more likely to wake up exactly when it requested, while a thread that was running recently and slept for only 10ms might run into scheduler timeslice issues. On Linux, threads that have been asleep for a while get a priority boost when they do wake up.
Using a function without sleep
in the name that blocks for 1 second is no better than using sleep
or this_thread::sleep_for
.
(Apparently you want another thread to be able to wake you up. This requirement is buried in the question, but yes a condition variable is a good portable way to do that.)
If you want to use pure ISO C++11, then std::this_thread::sleep_for
or std::this_thread::sleep_until
are your best bet. These are defined in standard header <thread>
.
sleep(3)
is a POSIX function (like nanosleep
), not part of ISO C++11. If that's not a problem for you, then feel free to use it if it's appropriate.
For portable high-precision OS-assisted sleep-for-an-interval, C++11 introducedstd::this_thread::sleep_for(const std::chrono::duration<Rep, Period> &sleep_duration)
(The cppreference page has a code example of using it.)
Blocks the execution of the current thread for at least the specified sleep_duration.
This function may block for longer than sleep_duration due to
scheduling or resource contention delays.
The standard recommends that a steady clock is used to measure the
duration. If an implementation uses a system clock instead, the wait
time may also be sensitive to clock adjustments.
To sleep until a clock reaches a specified time (possibly taking into account changes / corrections to the system time):
std::this_thread::sleep_until(const std::chrono::time_point<Clock,Duration>& sleep_time)
Blocks the execution of the current thread until specified
sleep_time
has been reached.
The clock tied to
sleep_time
is used, which means that adjustments of
the clock are taken into account. Thus, the duration of the block
might, but might not, be less or more thansleep_time - Clock::now()
at the time of the call, depending on the direction of the adjustment.
The function also may block for longer than until aftersleep_time
has
been reached due to scheduling or resource contention delays.
Notice that sleep_for
is meant to be unaffected by changes to the system clock, so it sleeps for that much real time.
But sleep_until
is supposed to let you wake up when the system clock reaches a given time, even if it did that by being adjusted (NTP or manual setting), if used with a clock other than steady_clock
.
Sleep gotchas: late / early wakeup
The caveats about possibly sleeping too long also apply to sleep
and nanosleep
, or any other OS-specific sleep or timeout (including the condition-variable approach in @Sebastian's answer), of course. It's unavoidable; a realtime OS can give you upper bounds on that extra delay, though.
You're already doing something like this with your 10ms sleeps:
Always assume that sleep
or whatever other function woke up late, and check the current time instead of using dead-reckoning in any case where that matters.
You can't build a reliable clock out of repeated sleep
.
e.g. don't build a count-down timer that sleeps for 1 second, decrements and displays a counter, then sleeps for another second. Unless it's just a toy and you don't care much about accuracy.
Some sleep functions such as POSIX sleep(3)
can also wake up early on a signal. If waking too early is a correctness problem, check the time and if necessary go back to sleep for the calculated interval. (Or use sleep_until
)
1
Peter - I might be being slow here... but I don't quite get what you are getting at. I think I am doing what you are suggesting already? I am usingstd::this_thread::sleep_for(...)
already and my loop (buried in my stopwatch class) is taking a time time-stamp such that after each interval it checks the actual time taken (and not just a series of sleep_for()'s added together. Is that what you mean?
â code_fodder
Aug 13 at 15:34
@code_fodder: I read the title and thought you were asking aboutsleep
. I only later realized you were already asking aboutthis_thread::sleep_for
but didn't have any good ideas for rewriting my answer. The requirement that another thread be able to wake you was totally buried in your question, and not obvious from the code. A conditional variable is a very good portable option there, otherwise do one sleep for the full duration. Like Damon says, multiple short sleeps aren't efficient. Not as bad as busy-waiting, but AFAIK short sleeps don't improve precision of the wake time.
â Peter Cordes
Aug 14 at 0:17
1
@PeterCordes Actaully I don't think I even added the requirement to wakeup... I probably should!.. good spot. But at least from your answer I can see that I started along the right direction : )
â code_fodder
Aug 14 at 8:11
@isanae: I updated it to maybe make more sense as an answer to this question. If you do just want to sleep, then avoiding functions withsleep
in the name is not useful if you're just going to use some other function in a way that makes it block for a fixed interval. @Damon's answer is better than mine, though.
â Peter Cordes
Aug 14 at 8:31
I retracted my downvote 8 hours ago after your edit. I haven't upvoted it because I don't think this is a good quality answer: it's confused, it has many unrelated sections and it is unclear what or where the actual answer is. I would suggest trimming most of it and cleaning up the layout.
â isanae
Aug 14 at 8:36
 |Â
show 3 more comments
up vote
3
down vote
up vote
3
down vote
You could busy-wait checking the time in a loop, until it reaches the time you're waiting for. That's obviously horrible, so don't do it. Sleeping for 10ms is somewhat better, but definitely poor design. (@Damon's answer has some good info.)
There's nothing wrong with using functions with sleep
in their name if that's the most useful thing for your program to do right then.
The suggestion to avoid sleep
is probably recommending against the general pattern of sleeping for a short time, checking if there's anything to do, then sleeping again. Instead, block waiting for an event with no timeout, or a very long timeout. (e.g. a GUI should wait for a keypress / click by calling a blocking function, with a timeout set to wake it up when it's time to autosave or whatever future thing is coming up next. You normally don't need a separate thread just to sleep, but you might if there's nowhere sensible to insert checks for the current time.)
Letting the OS wake you up when it's finally time to do anything is much better. This avoids context switches and cache pollution slowing down other programs and wasting power while you're spinning on short sleeps.
If you know there's nothing to do for some time, just sleep for that long with a single sleep. AFAIK, multiple short sleeps won't improve the accuracy of the wake-up time on mainstream OSes like Windows, Linux, or OS X. You might avoid an instruction-cache if your code had been waking up frequently, but if that amount of delay is a real problem you probably need a real-time OS and a much more sophisticated approach to timing.
If anything, a thread that's been sleeping for a long time is more likely to wake up exactly when it requested, while a thread that was running recently and slept for only 10ms might run into scheduler timeslice issues. On Linux, threads that have been asleep for a while get a priority boost when they do wake up.
Using a function without sleep
in the name that blocks for 1 second is no better than using sleep
or this_thread::sleep_for
.
(Apparently you want another thread to be able to wake you up. This requirement is buried in the question, but yes a condition variable is a good portable way to do that.)
If you want to use pure ISO C++11, then std::this_thread::sleep_for
or std::this_thread::sleep_until
are your best bet. These are defined in standard header <thread>
.
sleep(3)
is a POSIX function (like nanosleep
), not part of ISO C++11. If that's not a problem for you, then feel free to use it if it's appropriate.
For portable high-precision OS-assisted sleep-for-an-interval, C++11 introducedstd::this_thread::sleep_for(const std::chrono::duration<Rep, Period> &sleep_duration)
(The cppreference page has a code example of using it.)
Blocks the execution of the current thread for at least the specified sleep_duration.
This function may block for longer than sleep_duration due to
scheduling or resource contention delays.
The standard recommends that a steady clock is used to measure the
duration. If an implementation uses a system clock instead, the wait
time may also be sensitive to clock adjustments.
To sleep until a clock reaches a specified time (possibly taking into account changes / corrections to the system time):
std::this_thread::sleep_until(const std::chrono::time_point<Clock,Duration>& sleep_time)
Blocks the execution of the current thread until specified
sleep_time
has been reached.
The clock tied to
sleep_time
is used, which means that adjustments of
the clock are taken into account. Thus, the duration of the block
might, but might not, be less or more thansleep_time - Clock::now()
at the time of the call, depending on the direction of the adjustment.
The function also may block for longer than until aftersleep_time
has
been reached due to scheduling or resource contention delays.
Notice that sleep_for
is meant to be unaffected by changes to the system clock, so it sleeps for that much real time.
But sleep_until
is supposed to let you wake up when the system clock reaches a given time, even if it did that by being adjusted (NTP or manual setting), if used with a clock other than steady_clock
.
Sleep gotchas: late / early wakeup
The caveats about possibly sleeping too long also apply to sleep
and nanosleep
, or any other OS-specific sleep or timeout (including the condition-variable approach in @Sebastian's answer), of course. It's unavoidable; a realtime OS can give you upper bounds on that extra delay, though.
You're already doing something like this with your 10ms sleeps:
Always assume that sleep
or whatever other function woke up late, and check the current time instead of using dead-reckoning in any case where that matters.
You can't build a reliable clock out of repeated sleep
.
e.g. don't build a count-down timer that sleeps for 1 second, decrements and displays a counter, then sleeps for another second. Unless it's just a toy and you don't care much about accuracy.
Some sleep functions such as POSIX sleep(3)
can also wake up early on a signal. If waking too early is a correctness problem, check the time and if necessary go back to sleep for the calculated interval. (Or use sleep_until
)
You could busy-wait checking the time in a loop, until it reaches the time you're waiting for. That's obviously horrible, so don't do it. Sleeping for 10ms is somewhat better, but definitely poor design. (@Damon's answer has some good info.)
There's nothing wrong with using functions with sleep
in their name if that's the most useful thing for your program to do right then.
The suggestion to avoid sleep
is probably recommending against the general pattern of sleeping for a short time, checking if there's anything to do, then sleeping again. Instead, block waiting for an event with no timeout, or a very long timeout. (e.g. a GUI should wait for a keypress / click by calling a blocking function, with a timeout set to wake it up when it's time to autosave or whatever future thing is coming up next. You normally don't need a separate thread just to sleep, but you might if there's nowhere sensible to insert checks for the current time.)
Letting the OS wake you up when it's finally time to do anything is much better. This avoids context switches and cache pollution slowing down other programs and wasting power while you're spinning on short sleeps.
If you know there's nothing to do for some time, just sleep for that long with a single sleep. AFAIK, multiple short sleeps won't improve the accuracy of the wake-up time on mainstream OSes like Windows, Linux, or OS X. You might avoid an instruction-cache if your code had been waking up frequently, but if that amount of delay is a real problem you probably need a real-time OS and a much more sophisticated approach to timing.
If anything, a thread that's been sleeping for a long time is more likely to wake up exactly when it requested, while a thread that was running recently and slept for only 10ms might run into scheduler timeslice issues. On Linux, threads that have been asleep for a while get a priority boost when they do wake up.
Using a function without sleep
in the name that blocks for 1 second is no better than using sleep
or this_thread::sleep_for
.
(Apparently you want another thread to be able to wake you up. This requirement is buried in the question, but yes a condition variable is a good portable way to do that.)
If you want to use pure ISO C++11, then std::this_thread::sleep_for
or std::this_thread::sleep_until
are your best bet. These are defined in standard header <thread>
.
sleep(3)
is a POSIX function (like nanosleep
), not part of ISO C++11. If that's not a problem for you, then feel free to use it if it's appropriate.
For portable high-precision OS-assisted sleep-for-an-interval, C++11 introducedstd::this_thread::sleep_for(const std::chrono::duration<Rep, Period> &sleep_duration)
(The cppreference page has a code example of using it.)
Blocks the execution of the current thread for at least the specified sleep_duration.
This function may block for longer than sleep_duration due to
scheduling or resource contention delays.
The standard recommends that a steady clock is used to measure the
duration. If an implementation uses a system clock instead, the wait
time may also be sensitive to clock adjustments.
To sleep until a clock reaches a specified time (possibly taking into account changes / corrections to the system time):
std::this_thread::sleep_until(const std::chrono::time_point<Clock,Duration>& sleep_time)
Blocks the execution of the current thread until specified
sleep_time
has been reached.
The clock tied to
sleep_time
is used, which means that adjustments of
the clock are taken into account. Thus, the duration of the block
might, but might not, be less or more thansleep_time - Clock::now()
at the time of the call, depending on the direction of the adjustment.
The function also may block for longer than until aftersleep_time
has
been reached due to scheduling or resource contention delays.
Notice that sleep_for
is meant to be unaffected by changes to the system clock, so it sleeps for that much real time.
But sleep_until
is supposed to let you wake up when the system clock reaches a given time, even if it did that by being adjusted (NTP or manual setting), if used with a clock other than steady_clock
.
Sleep gotchas: late / early wakeup
The caveats about possibly sleeping too long also apply to sleep
and nanosleep
, or any other OS-specific sleep or timeout (including the condition-variable approach in @Sebastian's answer), of course. It's unavoidable; a realtime OS can give you upper bounds on that extra delay, though.
You're already doing something like this with your 10ms sleeps:
Always assume that sleep
or whatever other function woke up late, and check the current time instead of using dead-reckoning in any case where that matters.
You can't build a reliable clock out of repeated sleep
.
e.g. don't build a count-down timer that sleeps for 1 second, decrements and displays a counter, then sleeps for another second. Unless it's just a toy and you don't care much about accuracy.
Some sleep functions such as POSIX sleep(3)
can also wake up early on a signal. If waking too early is a correctness problem, check the time and if necessary go back to sleep for the calculated interval. (Or use sleep_until
)
edited Aug 14 at 15:13
BeeOnRope
23.9k873160
23.9k873160
answered Aug 13 at 12:09
Peter Cordes
107k15159277
107k15159277
1
Peter - I might be being slow here... but I don't quite get what you are getting at. I think I am doing what you are suggesting already? I am usingstd::this_thread::sleep_for(...)
already and my loop (buried in my stopwatch class) is taking a time time-stamp such that after each interval it checks the actual time taken (and not just a series of sleep_for()'s added together. Is that what you mean?
â code_fodder
Aug 13 at 15:34
@code_fodder: I read the title and thought you were asking aboutsleep
. I only later realized you were already asking aboutthis_thread::sleep_for
but didn't have any good ideas for rewriting my answer. The requirement that another thread be able to wake you was totally buried in your question, and not obvious from the code. A conditional variable is a very good portable option there, otherwise do one sleep for the full duration. Like Damon says, multiple short sleeps aren't efficient. Not as bad as busy-waiting, but AFAIK short sleeps don't improve precision of the wake time.
â Peter Cordes
Aug 14 at 0:17
1
@PeterCordes Actaully I don't think I even added the requirement to wakeup... I probably should!.. good spot. But at least from your answer I can see that I started along the right direction : )
â code_fodder
Aug 14 at 8:11
@isanae: I updated it to maybe make more sense as an answer to this question. If you do just want to sleep, then avoiding functions withsleep
in the name is not useful if you're just going to use some other function in a way that makes it block for a fixed interval. @Damon's answer is better than mine, though.
â Peter Cordes
Aug 14 at 8:31
I retracted my downvote 8 hours ago after your edit. I haven't upvoted it because I don't think this is a good quality answer: it's confused, it has many unrelated sections and it is unclear what or where the actual answer is. I would suggest trimming most of it and cleaning up the layout.
â isanae
Aug 14 at 8:36
 |Â
show 3 more comments
1
Peter - I might be being slow here... but I don't quite get what you are getting at. I think I am doing what you are suggesting already? I am usingstd::this_thread::sleep_for(...)
already and my loop (buried in my stopwatch class) is taking a time time-stamp such that after each interval it checks the actual time taken (and not just a series of sleep_for()'s added together. Is that what you mean?
â code_fodder
Aug 13 at 15:34
@code_fodder: I read the title and thought you were asking aboutsleep
. I only later realized you were already asking aboutthis_thread::sleep_for
but didn't have any good ideas for rewriting my answer. The requirement that another thread be able to wake you was totally buried in your question, and not obvious from the code. A conditional variable is a very good portable option there, otherwise do one sleep for the full duration. Like Damon says, multiple short sleeps aren't efficient. Not as bad as busy-waiting, but AFAIK short sleeps don't improve precision of the wake time.
â Peter Cordes
Aug 14 at 0:17
1
@PeterCordes Actaully I don't think I even added the requirement to wakeup... I probably should!.. good spot. But at least from your answer I can see that I started along the right direction : )
â code_fodder
Aug 14 at 8:11
@isanae: I updated it to maybe make more sense as an answer to this question. If you do just want to sleep, then avoiding functions withsleep
in the name is not useful if you're just going to use some other function in a way that makes it block for a fixed interval. @Damon's answer is better than mine, though.
â Peter Cordes
Aug 14 at 8:31
I retracted my downvote 8 hours ago after your edit. I haven't upvoted it because I don't think this is a good quality answer: it's confused, it has many unrelated sections and it is unclear what or where the actual answer is. I would suggest trimming most of it and cleaning up the layout.
â isanae
Aug 14 at 8:36
1
1
Peter - I might be being slow here... but I don't quite get what you are getting at. I think I am doing what you are suggesting already? I am using
std::this_thread::sleep_for(...)
already and my loop (buried in my stopwatch class) is taking a time time-stamp such that after each interval it checks the actual time taken (and not just a series of sleep_for()'s added together. Is that what you mean?â code_fodder
Aug 13 at 15:34
Peter - I might be being slow here... but I don't quite get what you are getting at. I think I am doing what you are suggesting already? I am using
std::this_thread::sleep_for(...)
already and my loop (buried in my stopwatch class) is taking a time time-stamp such that after each interval it checks the actual time taken (and not just a series of sleep_for()'s added together. Is that what you mean?â code_fodder
Aug 13 at 15:34
@code_fodder: I read the title and thought you were asking about
sleep
. I only later realized you were already asking about this_thread::sleep_for
but didn't have any good ideas for rewriting my answer. The requirement that another thread be able to wake you was totally buried in your question, and not obvious from the code. A conditional variable is a very good portable option there, otherwise do one sleep for the full duration. Like Damon says, multiple short sleeps aren't efficient. Not as bad as busy-waiting, but AFAIK short sleeps don't improve precision of the wake time.â Peter Cordes
Aug 14 at 0:17
@code_fodder: I read the title and thought you were asking about
sleep
. I only later realized you were already asking about this_thread::sleep_for
but didn't have any good ideas for rewriting my answer. The requirement that another thread be able to wake you was totally buried in your question, and not obvious from the code. A conditional variable is a very good portable option there, otherwise do one sleep for the full duration. Like Damon says, multiple short sleeps aren't efficient. Not as bad as busy-waiting, but AFAIK short sleeps don't improve precision of the wake time.â Peter Cordes
Aug 14 at 0:17
1
1
@PeterCordes Actaully I don't think I even added the requirement to wakeup... I probably should!.. good spot. But at least from your answer I can see that I started along the right direction : )
â code_fodder
Aug 14 at 8:11
@PeterCordes Actaully I don't think I even added the requirement to wakeup... I probably should!.. good spot. But at least from your answer I can see that I started along the right direction : )
â code_fodder
Aug 14 at 8:11
@isanae: I updated it to maybe make more sense as an answer to this question. If you do just want to sleep, then avoiding functions with
sleep
in the name is not useful if you're just going to use some other function in a way that makes it block for a fixed interval. @Damon's answer is better than mine, though.â Peter Cordes
Aug 14 at 8:31
@isanae: I updated it to maybe make more sense as an answer to this question. If you do just want to sleep, then avoiding functions with
sleep
in the name is not useful if you're just going to use some other function in a way that makes it block for a fixed interval. @Damon's answer is better than mine, though.â Peter Cordes
Aug 14 at 8:31
I retracted my downvote 8 hours ago after your edit. I haven't upvoted it because I don't think this is a good quality answer: it's confused, it has many unrelated sections and it is unclear what or where the actual answer is. I would suggest trimming most of it and cleaning up the layout.
â isanae
Aug 14 at 8:36
I retracted my downvote 8 hours ago after your edit. I haven't upvoted it because I don't think this is a good quality answer: it's confused, it has many unrelated sections and it is unclear what or where the actual answer is. I would suggest trimming most of it and cleaning up the layout.
â isanae
Aug 14 at 8:36
 |Â
show 3 more comments
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51817018%2fcan-you-implement-a-timer-without-a-sleep-in-it-using-standard-c-c11-only%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
6
You probably have a design issue and want to use a
std::future
instead. It has methodswait_for
andwait_until
.â Henri Menke
Aug 13 at 7:21
How accurate does the timer need to be? Nothing wrong with using
sleep_for
in this way.â Bathsheba
Aug 13 at 7:21
2
sleep is bad for "synchronize" multiple thread together, your usage might be fine.
â Jarod42
Aug 13 at 7:21
1
in "standard c++11" this is about all you have. If you widen your net to include posix then you can build an io loop based on pselect et al. boost.asio is built (sort of) this way.
â Richard Hodges
Aug 13 at 7:22
@HenriMenke I like the idea of wait_until(...), but I am thinking that if you wanted to exit the wait_until(...) part early I am not sure how you would do that?
â code_fodder
Aug 13 at 7:47