|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThreads are a powerful abstraction for allowing parallelized operations: graphical updates can happen while another thread is performing computations, two threads can handle two simultaneous network requests from a single process, and the list goes on. Since threads are pretty simple to understand, conceptually, but, practically, they are a cause for programmatic headaches, I decided to write this program to describe how to make use of threads. BackgroundTo understand this code completely, you need to have some basics on C# language. I used some forms and controls that are easy to understand. You can refer to the MS Visual Studio documentation to understand the Using the codeThe project AutoChess.sln consists of three classes:
This program, when executed, shows the previous grid. If one presses the (Start) button, those pieces start to move in random fashion. The King moves in any direction and the soldiers move in diagonals. Let's have a closer look at the code. We declared four threads, one for each piece: Thread t1, t2, t3, t4;
Then, we create our four threads: t1 = new Thread(ThreadStart(MoveWhiteKing));
t2 = new Thread(ThreadStart(MoveBlackKing));
t3 = new Thread(ThreadStart(MoveWhiteSoldier));
t4 = new Thread(ThreadStart(MoveBlackSoldier));
where WK = new WindowsApplication1.King (bs, WhiteKingPic, WhiteSoldierPic);
BK = new WindowsApplication1.King (bs, BlackKingPic, BlackSoldierPic);
WS = new WindowsApplication1.King (bs, WhiteSoldierPic,
WhiteKingPic, BlackKingPic);
BS = new WindowsApplication1.King (bs, BlackSoldierPic,
BlackKingPic, WhiteKingPic);
To start the four threads, the following code is put in private void button1_Click(object sender, System.EventArgs e)
{
this.button1.Enabled = false;
t1.Start();
t2.Start();
t3.Start();
t4.Start();
}
To understand more on how each thread works, let's have a closer look at the method referenced by the delegates. Let's take the private void MoveWhiteKing ()
{
lock( synchronizeVariable )
{
while(true)
{
Thread.Sleep(1000);
Monitor.PulseAll( synchronizeVariable );
WK.MoveKing(bs);
Monitor.Wait( synchronizeVariable );
}
}
}
We use the public static Object synchronizeVariable = "locking variable";
This variable is used to guarantee a certain behavior so that no two pieces move together. This is possible since there is only one thread that can grab the ConclusionI hope this example will be useful for many. I noticed that there are few examples discussing threads, especially those with the synchronization characteristic. So, I tried to make this example as easy as possible to understand. I will feel glad if there is anyone who wants to make suggestions or discuss on anything that I can help in.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||