android游戏循环中的同步 [英] Synchronization in android game loop

查看:66
本文介绍了android游戏循环中的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些用于学习目的的android基本游戏技术.

I'm reading about some android basic game techniques for learning purposes.

我遇到了一些代码,这些代码可以同步对游戏循环线程中使用的SurfaceHolder对象的访问,为什么这是必需的?

I came across some code that synchronizes the access to the SurfaceHolder object used on the game loop thread, why is this necessary?

sdk/samples/android-18/legacy/LunarLander LunarView.LunarThread类中找到的示例代码:

Sample code found in sdk/samples/android-18/legacy/LunarLander, LunarView.LunarThread class:

public void run() {
    while (mRun) {
        Canvas c = null;
        try {
            c = mSurfaceHolder.lockCanvas(null);
            synchronized (mSurfaceHolder) {
                if (mMode == STATE_RUNNING) updatePhysics();
                    synchronized (mRunLock) {
                        if (mRun) doDraw(c);
                    }
                }
        } finally {
            if (c != null) {
                mSurfaceHolder.unlockCanvasAndPost(c);
            }
        }
    }
}

因此,这段代码可以从mSurfaceHolder对象访问画布,然后在绘制画布时将其锁定. 为什么需要同步?

So this piece of code gets access to the canvas from the mSurfaceHolder object, which is then locked while the canvas is being drawn on. Why is the synchronization necessary?

我认为不是,因为请求画布并在其上绘制的唯一线程是运行游戏循环的线程.

I think it's not, since the only thread requesting the canvas and drawing on it is the thread where the game loop runs.

SurfaceHolder.lockCanvas()的文档化说它将获取一个内部锁,直到调用unlockCanvasAndPost()为止,那为什么还要额外的同步呢?

Also the documnetation of SurfaceHolder.lockCanvas() says that it will aquire an internal lock until the unlockCanvasAndPost() is called, then why the extra synchronization?

推荐答案

查看其余的源代码,SurfaceView线程之外的许多其他操作也在mSurfaceHolder上同步.因此,我的信念是mSurfaceHolder被用作方便的锁定"对象,以在线程与应用程序其余部分之间同步状态.

Looking at the rest of the source code, a number of other operations outside of the SurfaceView thread are also synchronized on mSurfaceHolder. My belief therefore is that mSurfaceHolder is being used as a convenient 'lock' object to synchronize state between the thread and the rest of the application.

这篇关于android游戏循环中的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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