多线程游戏 - 更新,渲染以及如何拆分它们 [英] Multi threaded game - updating, rendering, and how to split them

查看:238
本文介绍了多线程游戏 - 更新,渲染以及如何拆分它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在开发一款游戏引擎,并取得了不错的进步。但是,我的引擎是单线程的,将更新和渲染拆分为单独的线程的优点听起来是一个非常好的主意。

So, I'm working on a game engine, and I've made pretty good progress. However, my engine is single-threaded, and the advantages of splitting updating and rendering into separate threads sounds like a very good idea.

我该怎么做?单线程游戏引擎(概念上)很容易制作,你有一个循环,你更新 - >渲染 - >睡眠 - >重复。但是,我想不出一个打破更新和渲染分离的好方法,特别是如果我改变它们的更新速率(比如我经历更新循环25x一秒,并且有60fps用于渲染) - 如果我开始中途更新怎么办?通过渲染循环,反之亦然?

How should I do this? Single threaded game engines are (conceptually) very easy to make, you have a loop where you update -> render -> sleep -> repeat. However, I can't think of a good way to break updating and rendering apart, especially if I change their update rates (say I go through the update loop 25x a second, and have 60fps for rendering) - what if I begin updating halfway through a render loop, or vice versa?

推荐答案

将更新逻辑放在某种更新程序 worker class(实现 Runnable ),并将渲染器放入单独的worker类中。当您需要更新数据时,让Updater将该更新放入Updater和Producer共享的队列中。最方便的是使用已经具有内置多线程支持的队列,比如 BlockingQueue 的子类。例如代码,请参阅javadoc for BlockingQueue

Place your update logic in some kind of Updater worker class (implementing Runnable), and put renderer into separate worker class. When you need to update data, let Updater put that update into queue shared by both Updater and Producer. Most convenient would be to use queue which already have built-in multi-threaded support, like subclass of BlockingQueue. For example code, see javadoc for BlockingQueue.

如果需要渲染所有更改,使用队列是很自然的,甚至过时的。如果您只想渲染最新的更改,请使用 ConcurrentHashMap 而不是队列。

Using queue is natural if you need to render all changes, even obsolete ones. If you wish to render only the latest change, use ConcurrentHashMap instead of queue.

不要忘记制作你的更新不可变对象,所以在渲染时更新可能无法改变。

Don't forget to make your updates immutable objects, so there's no chance update can change while you render it.

正如Nirmal指出的那样,你可以使用某种线程池来限制线程数并简化线程的启动/停止。请参阅JDK中的 Executor 接口和 Executors 实用程序类,以查看此处的可用选项。

As Nirmal pointed out, you could use some kind of thread pool to limit number of threads and to simplify starting/stopping of threads. Refer to Executor interface and Executors utility class in JDK to see available options here.

这篇关于多线程游戏 - 更新,渲染以及如何拆分它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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