Uses Wait and Pulse to enable producer and consumer threads to cooperate in using a buffer

image_pdfimage_print
   

/*
Revised from code in "Computing with C# and the .NET Framework"

# Paperback: 753 pages
# Publisher: Jones and Bartlett Publishers, Inc.; Bk&CD-Rom edition (February 2003)
# Language: English
# ISBN: 0763723398
# Product Dimensions: 8.9 x 7.7 x 1.1 inches
*/


using System;
using System.Runtime.CompilerServices;
using System.Threading;  

  class Buffer {
    public const int size = 3;
    int[] buffer = new int [size];             
    int putpos=0;
    int getpos=0;
    int number=0;

    [MethodImpl(MethodImplOptions.Synchronized)]
    public void Put(int value) {
      if (number == size) {
        Console.WriteLine("Cannot put -- Buffer full");
        Monitor.Wait(this);
      }
      number++;
      buffer[putpos] = value;
      Console.WriteLine("Put "+value);
      putpos = (putpos + 1) % size;
      if (number == 1) Monitor.Pulse(this);         
    }

    [MethodImpl(MethodImplOptions.Synchronized)]
    public int Get() {
      if (number == 0) {
         Console.WriteLine("Buffer empty");
         Monitor.Wait(this);
      }
      number--;
      int n = buffer[getpos];
      Console.WriteLine("Get "+n);
      getpos = (getpos + 1) % size;
      if (number == size - 1) Monitor.Pulse(this);    
      return n;
    }
  }
  class Producer {
     Buffer buf;
     public Producer(Buffer b) { 
        buf = b;
        Thread thread = new Thread(new ThreadStart(Run));
        thread.Start();  
     }      
     public void Run() {
       for(; true; ) {
             buf.Put(0);
       }
     }
  }
  class Consumer {
     Buffer buf;
     public Consumer(Buffer b) { 
       buf = b;
       Thread thread = new Thread(new ThreadStart(Run));
       thread.Start();  
     }
     public void Run() {
       for (; true;) {
           buf.Get();
       }
     }
  }

public class PutGet {
  public static void Main(String[] args) {
    Buffer b = new Buffer();
    Producer p = new Producer(b);
    Consumer c = new Consumer(b);
  }
}
           
          


This entry was posted in Thread. Bookmark the permalink.