加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C 11线程:休眠一段时间

发布时间:2020-12-16 10:51:31 所属栏目:百科 来源:网络整理
导读:我正在尝试使用C 11线程为我的小游戏实现更新线程.我已经“尽可能快地”更新周期,但我想限制它说,每秒60次.我如何获得剩余的剩余时间? Core::Core(){ std::thread updateThread(update); // Start update thread}void Core::update(){ // TODO Get start ti
我正在尝试使用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>为你做转换.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读