|
Listing 5-5 extracted from chapter
Processes, threads and synchronization
Listing 5-4< > Listing 5-6
This listing can be compiled with the command line: csc.exe /target:exe Example_5_5.cs Errors: 0 Warnings: 0
Example_5_5.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++ ) {
Interlocked.Increment( ref counter );
System.Console.WriteLine( "counter++ {0}" , counter );
Thread.Sleep( 10 );
}
}
static void f2() {
for ( int i = 0; i < 5; i++ ) {
Interlocked.Decrement( ref counter );
System.Console.WriteLine( "counter-- {0}" , counter );
Thread.Sleep( 10 );
}
}
}
Copyright Patrick Smacchia 2006 2007
|