C ++ - 每X毫秒执行一次函数 [英] C++ - Execute function every X milliseconds

查看:242
本文介绍了C ++ - 每X毫秒执行一次函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎找不到一个很好的答案:

I can't seem to find a good answer to this:

我在做一个游戏,我希望逻辑循环与图形分开循环。换句话说,我想让游戏每X毫秒经过一个循环,无论它显示多少帧/秒。

I'm making a game, and I want the logic loop to be separate from the graphics loop. In other words I want the game to go through a loop every X milliseconds regardless of how many frames/second it is displaying.

显然,他们都将分享很多变量,所以我不能有一个线程/计时器来回传递一个变量...我基本上只是寻找一种方法在后台有一个定时器,每X毫秒发出一个标志执行逻辑循环,无论图形循环在哪里。

Obviously they will both be sharing a lot of variables, so I can't have a thread/timer passing one variable back and forth... I'm basically just looking for a way to have a timer in the background that every X milliseconds sends out a flag to execute the logic loop, regardless of where the graphics loop is.

我打开任何建议。它似乎最好的选择是有2个线程,但我不知道什么最好的方式之间沟通,是没有不断同步大量的数据。

I'm open to any suggestions. It seems like the best option is to have 2 threads, but I'm not sure what the best way to communicate between them is, without constantly synchronizing large amounts of data.

推荐答案

你可以很好地做多线程,让你的世界观交换每一个刻度。下面是它的工作原理:

You can very well do multithreading by having your "world view" exchanged every tick. So here is how it works:


  1. 您的当前世界视图由一个智能指针指向,

  2. 您的逻辑创建您的(第一个)世界视图,发布它并安排渲染器。

  3. 您的渲染器获取指向您世界视图的指针的副本并呈现它(记住,只读)

  4. 同时,您的逻辑创建一个新的略微不同的世界视图。

  5. 完成后,将指针交换到当前世界视图,将其作为当前世界视图发布。

  6. 即使渲染器仍在忙于旧世界视图,也不需要锁定。

  7. 最终渲染器完成渲染(旧)世界。

  8. 与此同时,...(goto步骤4)

  1. Your current world view is pointed to by a single smart pointer and is read only, so no locking is necessary.
  2. Your logic creates your (first) world view, publishes it and schedules the renderer.
  3. Your renderer grabs a copy of the pointer to your world view and renders it (remember, read-only)
  4. In the meantime, your logic creates a new, slightly different world view.
  5. When it's done it exchanges the pointer to the current world view, publishing it as the current one.
  6. Even if the renderer is still busy with the old world view there is no locking necessary.
  7. Eventually the renderer finishes rendering the (old) world. It grabs the new world view and starts another run.
  8. In the meantime, ... (goto step 4)

您需要的唯一锁定是您发布或抓取指针到世界的时间。作为替代,你可以做原子交换,但是你必须确保你使用智能指针,可以做到这一点。

The only locking you need is for the time when you publish or grab the pointer to the world. As an alternative you can do atomic exchange but then you have to make sure you use smart pointers that can do that.

这篇关于C ++ - 每X毫秒执行一次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆