In my previous Developer Diary I discussed the problems that can arise from threaded development particularly as outlined in the example. In this post I discuss locks, what they are and how they can fix the problems with the example.
What are Locks?
The lock is one of the primary synchronization primitives in .NET. Locks are largely used to control access to a particular part of code (commonly called a critical section).
When a thread owns a lock no other thread is able to use the lock and execute the code protected by the lock. This results in the other threads waiting for the first thread to release its ownership. Once the first thread releases ownership one of the waiting threads will then own the lock and continue executing.
The basic way to create and use a lock is as follows:
class SomeClass {
private object syncLock = new object( );
public void SomeMethod( ) {
lock( syncLock ) {
}
}
}
The variable syncLock can actually be of any reference type. This means primitive and value types (such as int, float, Vector3, etc) cannot be used.
Updating Our Example
So how do locks help given our example? First let's update the code from the example in the previous Developer Diary (Note: the fully updated source is at the end of this post).
First we need our class-level shared lock.
private object enemyDataLock = new object( );
After that we need to update the code in EnemyAIThreadMethod to lock just the area that updates the data that is used in the Draw method. You want to lock as little as possible otherwise you may slow down other threads who are also trying to use the lock. For example, if the Thread.Sleep( 10 ); statement was in the lock block then we would make it more difficult for the Draw method to maintain a high frame rate.
private void EnemyAIThreadMethod( ) {
while( !isStopping ) {
lock( enemyDataLock ) {
enemyRotation -= 0.01f;
enemyVelocity += new Vector3( 1, 0, 1 );
enemyPosition += enemyVelocity;
}
Thread.Sleep( 10 );
}
}
Finally we update the Draw method. At first glance you may consider simply putting a lock around the entire foreach block to ensure that we use the same values for enemyRotation and enemyPosition for each mesh in the model. The Draw method would look like this:
public override void Draw( GameTime gameTime ) {
Matrix[ ] transforms = new Matrix[ enemyModel.Bones.Count ];
enemyModel.CopyAbsoluteBoneTransformsTo( transforms );
lock( enemyDataLock ) {
foreach( ModelMesh mesh in enemyModel.Meshes ) {
foreach( BasicEffect effect in mesh.Effects ) {
effect.EnableDefaultLighting( );
effect.World = transforms[ mesh.ParentBone.Index ]
* Matrix.CreateRotationY( enemyRotation )
* Matrix.CreateTranslation( enemyPosition );
effect.View = Matrix.CreateLookAt(
cameraPosition,
Vector3.Zero,
Vector3.Up );
effect.Projection = Matrix.CreatePerspectiveFieldOfView(
MathHelper.ToRadians( 45.0f ),
aspectRatio,
1.0f,
10000.0f );
}
mesh.Draw( );
}
}
base.Draw( gameTime );
}
That is a lot of code to lock. Remember you want to lock as little as possible. A better approach is to create local copies of the data and only lock the point where the data is copied. Our new Draw method looks as follows:
public override void Draw( GameTime gameTime ) {
Matrix[ ] transforms = new Matrix[ enemyModel.Bones.Count ];
enemyModel.CopyAbsoluteBoneTransformsTo( transforms );
Vector3 enemyPositionCopy;
float enemyRotationCopy;
lock( enemyDataLock ) {
enemyPositionCopy = enemyPosition;
enemyRotationCopy = enemyRotation;
}
foreach( ModelMesh mesh in enemyModel.Meshes ) {
foreach( BasicEffect effect in mesh.Effects ) {
effect.EnableDefaultLighting( );
effect.World = transforms[ mesh.ParentBone.Index ]
* Matrix.CreateRotationY( enemyRotationCopy )
* Matrix.CreateTranslation( enemyPositionCopy );
effect.View = Matrix.CreateLookAt(
cameraPosition,
Vector3.Zero,
Vector3.Up );
effect.Projection = Matrix.CreatePerspectiveFieldOfView(
MathHelper.ToRadians( 45.0f ),
aspectRatio,
1.0f,
10000.0f );
}
mesh.Draw( );
}
base.Draw( gameTime );
}
}
This seriously cuts down on the amount of code locked allowing both threads to run more quickly. As a note, the Vector3 type is a value type (struct), instead of a reference type (class). This means the line enemyPositionCopy = enemyPosition; isn't simply assigning a reference, but making a field by field copy of the Vector3 members. This is an important distinction. If we had reference types then other code would need to be considered. I'll cover that in my next article.
Why Does It Work?
I mentioned in the previous article that our example needed updating to cover two problems.
The first problem was uncontrolled access to the data. This is fixed by the lock statements. The use of a lock prevents the Draw thread from using the enemy data while the data is being updated in the EnemyAIMethod thread and conversely the EnemyAIMethod can't update the values while the Draw method is copying them.
The second problem was getting around .NET's memory and synchronization model. The reason this isn't an issue is due to how locks work. I'll attempt a simple explanation since it is much more complicated than I'm describing. Locks explicitly indicate to .NET that there is threaded code so that certain optimizations will not occur. Some optimizations, such as the caching of data in processor and system caches, aren't an issue because a lock ensures that modified data makes it in and out of main memory.
As you may have guessed using locks incurs a performance penalty. However, it can be a small price to pay for correctness. More advanced options are available, but they are harder to code for. I'll outline one such approach in my next post.
In Summary
Locks are an important part of threading in .NET but, as with all things, they have their advantages and disadvantages.
Advantages of locks:
Disadvantages of locks:
- Is fairly expensive to execute
- Easier to create deadlock situations
What is a Deadlock?
It is best to discuss deadlocks when you have an example. Fortunately the XNA example code we have been using isn't subject to deadlocks, but the following piece of code is:
private object syncLockA = new object( );
private object syncLockB = new object( );
private void ThreadMethodOne( ) {
while( !isStopping ) {
lock( syncLockA ) {
lock( syncLockB ) {
}
}
}
}
private void ThreadMethodTwo( ) {
while( !isStopping ) {
lock( syncLockB ) {
lock( syncLockA ) {
}
}
}
}
The potential for deadlocks occur when two or more threads have two or more locks they are sharing. In the above code a deadlock can occur if we have a thread executing in ThreadMethodOne that is currently trying to acquire syncLockB after having acquired syncLockA, and we have another thread executing in ThreadMethodTwo trying to acquire syncLockA after having acquired syncLockB. These threads are now stuck forever since they are waiting for the other thread to release the additional lock needed.
That's a deadlock. Once you have multiple threads and multiple locks you need to be extra careful with your code.
Follow-on Posts
I hope this post gave you a good overview of how to use locks in .NET. In my next post I'll talk about another mechanism that can be used to handle our example, as well as some pointers for additional .NET threading details and recommendations.
Complete Updated Example Source Code
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
namespace SampleThreading {
public class ThreadedEnemyComponent : DrawableGameComponent {
private ContentManager content;
Vector3 cameraPosition = new Vector3( 0.0f, 50.0f, -5000.0f );
float aspectRatio = 640.0f / 480.0f;
private Thread enemyAIThread = null;
private volatile bool isStopping = false;
private object enemyDataLock = new object( );
private Model enemyModel;
private Vector3 enemyVelocity = Vector3.Zero;
private Vector3 enemyPosition = Vector3.Zero;
private float enemyRotation = 0.0f;
public ThreadedEnemyComponent( Game theGame )
: base( theGame ) {
content = new ContentManager( this.Game.Services );
}
public override void Initialize( ) {
base.Initialize( );
enemyAIThread = new Thread( EnemyAIThreadMethod );
enemyAIThread.Start( );
}
protected override void Dispose( bool disposing ) {
try {
isStopping = true;
if( disposing ) {
if( enemyAIThread != null ) {
enemyAIThread.Join( );
enemyAIThread = null;
}
}
} finally {
base.Dispose( disposing );
}
}
protected override void LoadGraphicsContent( bool loadAllContent ) {
if( loadAllContent ) {
enemyModel = this.content.Load<Model>( @"Content\Models\
enemyModel" );
}
}
protected override void UnloadGraphicsContent( bool unloadAllContent ) {
if( unloadAllContent == true ) {
content.Unload( );
}
}
private void EnemyAIThreadMethod( ) {
while( !isStopping ) {
lock( enemyDataLock ) {
enemyRotation -= 0.01f;
enemyVelocity += new Vector3( 1, 0, 1 );
enemyPosition += enemyVelocity;
}
Thread.Sleep( 10 );
}
}
public override void Draw( GameTime gameTime ) {
Matrix[ ] transforms = new Matrix[ enemyModel.Bones.Count ];
enemyModel.CopyAbsoluteBoneTransformsTo( transforms );
Vector3 enemyPositionCopy;
float enemyRotationCopy;
lock( enemyDataLock ) {
enemyPositionCopy = enemyPosition;
enemyRotationCopy = enemyRotation;
}
foreach( ModelMesh mesh in enemyModel.Meshes ) {
foreach( BasicEffect effect in mesh.Effects ) {
effect.EnableDefaultLighting( );
effect.World = transforms[ mesh.ParentBone.Index ]
* Matrix.CreateRotationY( enemyRotationCopy )
* Matrix.CreateTranslation( enemyPositionCopy );
effect.View = Matrix.CreateLookAt(
cameraPosition,
Vector3.Zero,
Vector3.Up );
effect.Projection = Matrix.CreatePerspectiveFieldOfView(
MathHelper.ToRadians( 45.0f ),
aspectRatio,
1.0f,
10000.0f );
}
mesh.Draw( );
}
base.Draw( gameTime );
}
}
}