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-26 extracted from chapter
Processes, threads and synchronization
Listing 5-25< > Listing 5-27
This listing can be compiled with the command line: csc.exe /target:exe Example_5_26.cs Errors: 0 Warnings: 0
Example_5_26.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 LocalDataStoreSlot dSlot;
static bool fServer() {
int counter = (int) Thread.GetData( dSlot );
counter++;
Thread.SetData( dSlot, counter );
return !( counter == MAXCALL );
}
static void ThreadProc() {
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 );
dSlot = Thread.AllocateDataSlot();
for ( int i = 0; i < NTHREAD; i++ ) {
Thread thread = new Thread( ThreadProc );
thread.Start();
}
Thread.Sleep( PERIOD * (MAXCALL + 1) );
Console.WriteLine( "Thread#{0} I'm the main thread, bye.",
Thread.CurrentThread.ManagedThreadId );
}
}
Copyright Patrick Smacchia 2006 2007
|