Solve Producer Consumer Problem - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Producer Consumer

Description

Solve Producer Consumer Problem

Demo Code

using System;/* www . ja  va2  s  . c o m*/
using System.Threading;
public class Factory {
   private int[]  Widgets = new int[100];
   private int    WidgetIndex = 0;
   private AutoResetEvent NewWidgetEvent = new AutoResetEvent( false );
   protected void Producer( ) {
      while( true ) {   //run forever
          lock( this ) {
             if( WidgetIndex < 100 ) {
                Widgets[ WidgetIndex ] = 1;
                Console.WriteLine("Widget {0} Produced", WidgetIndex++ );
                NewWidgetEvent.Set( );
             }
          }
          Thread.Sleep( (new Random()).Next( 5 ) * 1000 );
       }
    }
    protected void Consumer( ) {
       while( true ) {
          NewWidgetEvent.WaitOne( );
          int iWidgetIndex = 0;
          lock( this ) {
             iWidgetIndex = --this.WidgetIndex;
             Console.WriteLine("Consuming widget {0}", iWidgetIndex );
             Widgets[ iWidgetIndex-- ] = 0;
          }
       }
    }
    public void Run( ) {
       //Create 3 producers
       for( int i = 0; i < 3; i++ ) {
          Thread producer = new Thread( new ThreadStart( Producer ) );
          producer.Start( );
       }
       //Create 3 consumers
       for( int i = 0; i < 3; i++ ) {
          Thread consumer = new Thread( new ThreadStart( Consumer ) );
          consumer.Start( );
       }
    }
    public static void Main( ) {
       Factory factory = new Factory( );
       factory.Run( );
    }
}

Result


Related Tutorials