|
Listing 5-15 extracted from chapter
Processes, threads and synchronization
Listing 5-14< > Listing 5-16
This listing can be compiled with the command line: csc.exe /target:exe Example_5_15.cs Errors: 0 Warnings: 0
Example_5_15.cs
using System;
using System.Threading;
class Program {
static Semaphore semaphore;
static void Main() {
// Initial number of free slots : 2.
// Maximal number of slots used simulteanously : 5.
// Number of slot owned by the main thread : 3 (5-2).
semaphore = new Semaphore( 2, 5 );
for ( int i = 0; i < 3; ++i ) {
Thread t = new Thread( WorkerProc );
t.Name = "Thread" + i;
t.Start();
Thread.Sleep( 30 );
}
}
static void WorkerProc() {
for ( int j = 0; j < 3; j++ ) {
semaphore.WaitOne();
Console.WriteLine( Thread.CurrentThread.Name + ": Begin" );
Thread.Sleep( 200 ); // Simulate a 200 milliseconds task.
Console.WriteLine( Thread.CurrentThread.Name + ": End" );
semaphore.Release();
}
}
}
Copyright Patrick Smacchia 2006 2007
|