C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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);
    }
}

解决方法

这是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);
}

任何时候你使用< chrono>,并且你看到你是手动转换单位,你就可以立即或在将来的维护中打开自己的bug.设< chrono>为你做转换.

大佬总结

以上是大佬教程为你收集整理的C 11线程:休眠一段时间全部内容,希望文章能够帮你解决C 11线程:休眠一段时间所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。