Dinning Philosophers - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Thread

Description

Dinning Philosophers

Demo Code

using System;//from ww  w.j a va2  s . c om
using System.Threading;
public struct PhilosopherData {
   public int            PhilosopherId;
   public Mutex         RightChopStick;
   public Mutex         LeftChopStick;
   public int            AmountToEat;
   public int            TotalFood;
}
public class Philosopher : WorkerThread
{
   public Philosopher( object data ) : base( data ) { }
   protected override void Run( ) {
      PhilosopherData pd = (PhilosopherData)Data;
      Random r = new Random( pd.PhilosopherId );
      Console.WriteLine("Philosopher {0} ready", pd.PhilosopherId );
      WaitHandle[] chopSticks =  new WaitHandle[] { pd.LeftChopStick, pd.RightChopStick };
      while( pd.TotalFood > 0 ) {
         WaitHandle.WaitAll( chopSticks );
         Console.WriteLine("Philosopher {0} eating {1} of {2} food", pd.PhilosopherId, pd.AmountToEat, pd.TotalFood );
         pd.TotalFood -= pd.AmountToEat;
         Thread.Sleep( r.Next(1000,5000) );
         Console.WriteLine("Philosopher {0} thinking", pd.PhilosopherId);
         pd.RightChopStick.ReleaseMutex( );
         pd.LeftChopStick.ReleaseMutex( );
         Thread.Sleep( r.Next(1000,5000) );
      }
      Console.WriteLine("Philosopher {0} finished", pd.PhilosopherId );
   }
}
public class Restaurant {
   public static void Main( ) {
      Mutex[] chopSticks = new Mutex[5];
      for( int i = 0; i < 5; i++ )
         chopSticks[i] = new Mutex( false );
      for( int i = 0; i < 5; i++ ) {
         PhilosopherData pd;
         pd.PhilosopherId = i + 1;
         pd.RightChopStick = chopSticks[ i - 1 >= 0 ? ( i - 1 ) : 4 ];
         pd.LeftChopStick = chopSticks[i];
         pd.AmountToEat = 5;
         pd.TotalFood = 35;
         Philosopher p = new Philosopher( pd );
         p.Start( );
      }
      Console.ReadLine( );
   }
}
public abstract class WorkerThread {
   private object   ThreadData;
   private Thread   thisThread;
   public object Data {
      get { return ThreadData; }
      set { ThreadData = value; }
   }
   public object IsAlive {
      get { return thisThread == null ? false : thisThread.IsAlive; }
   }
   public WorkerThread( object data ) {
      this.ThreadData = data;
   }
   public WorkerThread( ) {
      ThreadData = null;
   }
   public void Start( ) {
      thisThread = new Thread( new ThreadStart( this.Run ) );
      thisThread.Start();
   }
   public void Stop( ) {
      thisThread.Abort( );
      while( thisThread.IsAlive ) ;
      thisThread = null;
   }
   protected abstract void Run( );
}

Result


Related Tutorials