C++ 11线程:休眠一段时间

man*_*eak 3 c++ multithreading c++11

我正在尝试使用C++ 11线程为我的小游戏实现更新线程.我已经"尽可能快地"更新周期,但我想限制它说,每秒60次.如何剩下剩余的时间?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

How*_*ant 11

这是Pete的正确答案(我已经投票),但是有一些代码可以显示它比其他答案更容易完成:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

无论何时使用<chrono>,并且您看到您手动转换单元,您都可以立即或在将来的维护中打开自己的bug.让我们<chrono>为你做转换.


Pet*_*ker 5

如果您正在使用C++ 11线程,那么您不仅限于该_sleep函数所做的任何事情.C++ 11线程具有sleep_for持续时间(即,休眠10秒),并且sleep_until需要一个时间点(即,睡到下周四).对于必须以固定间隔唤醒的线程,是可行sleep_until的方法.睡到下一个叫醒时间.