|
Listing 5-6 extracted from chapter
Processes, threads and synchronization
Listing 5-5< > Listing 5-7
This listing can be compiled with the command line: csc.exe /target:exe Example_5_6.cs Errors: 0 Warnings: 0
Example_5_6.cs
using System.Threading;
class Program {
static long counter = 1;
static void Main() {
Thread t1 = new Thread( f1 );
Thread t2 = new Thread( f2 );
t1.Start(); t2.Start(); t1.Join(); t2.Join();
}
static void f1() {
for (int i = 0; i < 5; i++){
Monitor.Enter( typeof( Program ) );
try{
counter *= counter;
}
finally{ Monitor.Exit( typeof( Program ) ); }
System.Console.WriteLine("counter^2 {0}", counter);
Thread.Sleep(10);
}
}
static void f2() {
for (int i = 0; i < 5; i++){
Monitor.Enter( typeof( Program ) );
try{
counter *= 2;
}
finally{ Monitor.Exit( typeof( Program ) ); }
System.Console.WriteLine("counter*2 {0}", counter);
Thread.Sleep(10);
}
}
}
Copyright Patrick Smacchia 2006 2007
|