Android loop sync

I read about some methods of playing Android for training.

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

Example 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); } } } } 

Thus, this piece of code accesses the canvas from the mSurfaceHolder object, which then locks while drawing the canvas. Why do I need synchronization?

I think this is not the case, since the only thread requesting the canvas and drawn on it is the thread in which the game loop is running.

Also , the documnetation document of SurfaceHolder.lockCanvas () says that it will use the internal lock until unlockCanvasAndPost () is called, then why is there additional synchronization?

+4
source share
2 answers

If you look at the link you provided, full quote:

If null does not return, this function internally holds the lock until a corresponding call to unlockCanvasAndPost (Canvas) is called , preventing the SurfaceView from creating, destroying, or modifying the surface while it is drawing.

My emphasis is that reading is not on the list.

So lockCanvas does not stop reading. I suppose that additional synchronization is intended to ensure that other reads are not being read at that time, which makes sense because you are calling updatePhysics , which can be quite annoying for other readers.

+1
source

Looking at the rest of the source code, a number of other operations outside the SurfaceView stream are also synchronized to mSurfaceHolder . Therefore, I believe that mSurfaceHolder used as a convenient “lock” object to synchronize state between the thread and the rest of the application.

+1
source

All Articles