Nice TWiki > Doc > CodeExamples > ProducerConsumerBeginnerExample TWiki webs:
Dev | Doc | Main | TWiki | Sandbox
Doc . { Changes | Index | Search | Go }
/* Please try the NoviceExamples before the BeginnerExamples

   requires Nice 0.9.3 or above

To compile:   
   nicec --sourcepath .. -d . -a prodcons.jar prodcons

To run:
   java -jar prodcons.jar 
*/


var int produced = 0; 
var int consumed = 0;   

void main(String[] args){
   let n = 10;    
   let b = new SharedBuffer();   
   let producer = new Producer(buffer: b, countdown: n);
   let consumer = new Consumer(buffer: b, countdown: n);

   producer.start;
   consumer.start;
   try {  producer.join;  }  catch (InterruptedException e) { }
   try {  consumer.join;  }  catch (InterruptedException e) { }
   
   println(produced + " " + consumed);
}


class SharedBuffer {
   int contents = -1;
   boolean available = false;

   int get();
   get() {
      while (available == false) {
         try { this.wait(); } catch (InterruptedException e) { }
      }
      available = false;
      this.notifyAll;
      return contents;
   }

   void put(int value);
   put(value)  {
      while (available == true) {
         try { this.wait(); } catch (InterruptedException e) { }
      }
      contents = value;
      available = true;
      this.notifyAll;
   }
}


class Producer extends Thread {
   SharedBuffer buffer;
   int countdown;

   run() {
      while (countdown-- > 0) {
         synchronized(buffer) { 
            buffer.put(countdown); 
            println("produced " + countdown);  // check            
         }               
         ++produced;
      }
   }
}


class Consumer extends Thread {
   SharedBuffer buffer;
   int countdown;

   run() {
      var value = 0;
      while (countdown-- > 0) {
         synchronized(buffer) { 
            value = buffer.get; 
            println("\t" + "consumed " + value); // check 
         }
         ++consumed;
      }    
   }    
}


/* Notes - language
Compare with Java at the "Win32 Language Shootout"

*/

-- IsaacGouy - 17 Sep 2003

Topic ProducerConsumerBeginnerExample . { Edit | Attach | Ref-By | Printable | Diffs | r1.3 | > | r1.2 | > | r1.1 | More }
Revision r1.3 - 10 Jan 2004 - 19:07 GMT - IsaacGouy
Parents: WebHome > CodeExamples
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.