C++11 Threads: sleep for a remaining time
c++, c++11, multithreading
Solution
Here is Pete's correct answer (which I up-voted) but with some code thrown in to show how much easier it is done than the other answers:
// desired frame rate
typedef std::chrono::duration<int, std::ratio<1, 60>> frame_duration;
void Core::update()
{
// Get start time
auto start_time = std::chrono::steady_clock::now();
// Get end time
auto end_time = start_time + frame_duration(1);
// Here happens the actual update stuff
// Sleep if necessary
std::this_thread::sleep_until(end_time);
}
Any time you're using `<chrono>`, and you see you're manually converting units, you're opening yourself up to bugs, either immediately, or in future maintenance. Let `<chrono>` do the conversions for you.
Problem
I'm trying to implement an update thread for my small game with C++11 threads. I've got the update cycle going on "as fast as possible", but I'd like to limit it to say, 60 times per second. How do I get the remaining time left? ``` Core::Core() { std::thread updateThread(update); // Start update thread } void Core::update() { // TODO Get start time // Here happens the actual update stuff // TODO Get end time // double duration = ...; // Get the duration // Sleep if necessary if(duration < 1.0 / 60.0) { _sleep(1.0 / 60.0 - duration); } } ```