This is not as simple as it seems, because although I do not think so, in some situations, calls to wait for threads may wake up earlier than requested.
To combat this, I considered it necessary to put a wait code in a loop so that when the thread wakes up, it checks whether the timeout has expired. If this is not re-starting sleep:
using clock = std::chrono::steady_clock; // for an easier life // set the wake-up time for 10 seconds in the future auto timeout = clock::now() + std::chrono::seconds(10); for(;;) { // loop in-case of early wakeup while(clock::now() < timeout) std::this_thread::sleep_until(timeout); timeout += std::chrono::seconds(10); // reset timer // do something useful (like print the time) auto timer = std::time(0); std::cout << "loop: " << std::ctime(&timer) << '\n'; }
Using std::this_thread::sleep_until() , the loop does not consume CPU time while it waits for 10 seconds to finish.
This can be wrapped up in a neat little class like this:
class wait_timer { using clock = std::chrono::steady_clock; clock::duration time_to_wait; clock::time_point timeout = clock::now(); public: wait_timer(std::chrono::milliseconds ms) : time_to_wait(ms), timeout(clock::now() + ms) {} void wait() { while(clock::now() < timeout) std::this_thread::sleep_until(timeout); timeout += time_to_wait;
Galik source share