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-16 extracted from chapter Processes, threads and synchronization


Listing 5-15<     > Listing 5-17


This listing can be compiled with the command line:
csc.exe /target:exe Example_5_16.cs
Errors: 0 Warnings: 0


Example_5_16.cs
using System;
using System.Threading;
class Program {
   static int theResource   = 0;
   static ReaderWriterLock rwl = new ReaderWriterLock();
   static void Main() {
      Thread tr0 = new Thread( ThreadReader );
      Thread tr1 = new Thread( ThreadReader );
      Thread tw = new Thread( ThreadWriter );
      tr0.Start(); tr1.Start(); tw.Start();
      tr0.Join();  tr1.Join();  tw.Join();
   }
   static void ThreadReader() {
      for int = 0; i < 3; i++ )
         try{
            // AcquireReaderLock() raises an 
            // ApplicationException when timed out.
            rwl.AcquireReaderLock(1000);
            Console.WriteLine("Begin Read  theResource = {0}",theResource);
            Thread.Sleep(10);
            Console.WriteLine("End   Read  theResource = {0}",theResource);
            rwl.ReleaseReaderLock();
         }
         catch ApplicationException ) { /* ... */ }
   }
   static void ThreadWriter() {
      for (int = 0; i < 3; i++)
         try{
            // AcquireReaderLock() raises an 
            // ApplicationException when timed out.
            rwl.AcquireWriterLock(1000);
            Console.WriteLine("Begin Write theResource = {0}",theResource);
            Thread.Sleep(100);
            theResource  ++;
            Console.WriteLine("End   Write theResource = {0}",theResource);
            rwl.ReleaseWriterLock();
         }
         catch ApplicationException ) { /* ... */ }
   }
}	
Copyright Patrick Smacchia 2006 2007