Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press
Buy directly from Paradoxal Press at $33.99 (Save 43%)
Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA
|
Listing 5-25 extracted from chapter
Processes, threads and synchronization
Listing 5-24< > Listing 5-26
This listing can be compiled with the command line: csc.exe /target:exe Example_5_25.cs Errors: 0 Warnings: 0
Example_5_25.cs
using System;
using System.Threading;
class Program {
static readonly int NTHREAD = 3; // 3 threads to create.
// 2 calls to fServer() for each thread created.
static readonly int MAXCALL = 2;
static readonly int PERIOD = 1000; // 1 second between calls.
static bool fServer() {
LocalDataStoreSlot dSlot = Thread.GetNamedDataSlot( "Counter" );
int counter = (int) Thread.GetData( dSlot );
counter++;
Thread.SetData( dSlot, counter );
return !( counter == MAXCALL );
}
static void ThreadProc() {
LocalDataStoreSlot dSlot = Thread.GetNamedDataSlot( "Counter" );
Thread.SetData( dSlot, (int) 0 );
do{
Thread.Sleep( PERIOD );
Console.WriteLine(
"Thread#{0} I've called fServer(), Counter = {1}",
Thread.CurrentThread.ManagedThreadId ,
(int)Thread.GetData(dSlot));
} while ( fServer() );
Console.WriteLine("Thread#{0} bye",
Thread.CurrentThread.ManagedThreadId );
}
static void Main() {
Console.WriteLine( "Thread#{0} I'm the main thread, hello world",
Thread.CurrentThread.ManagedThreadId );
Thread.AllocateNamedDataSlot( "Counter" );
Thread thread;
for ( int i = 0; i < NTHREAD; i++ ) {
thread = new Thread( ThreadProc );
thread.Start();
}
// We don't implement a mechanism to wait for child threads
// completion, thus, we are waiting for a while.
Thread.Sleep( PERIOD * (MAXCALL + 1) );
Thread.FreeNamedDataSlot( "Counter" );
Console.WriteLine( "Thread#{0} I'm the main thread, bye.",
Thread.CurrentThread.ManagedThreadId );
}
}
Copyright Patrick Smacchia 2006 2007
|