summaryrefslogtreecommitdiff
path: root/test/pending/shootout/prodcons.scala
blob: d48d3e94d841ade8ccee40f1af1ba403744c6c82 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* The Computer Language Shootout 
   http://shootout.alioth.debian.org/
   contributed by Isaac Gouy (Scala novice)
*/

import concurrent.SyncVar;
import concurrent.ops._;

object prodcons {
   def main(args: Array[String]) = {
      val n = toPositiveInt(args);
      val buffer = new SharedBuffer();
      var p = 0;
      var c = 0;
      val cDone = new SyncVar[Boolean];

      spawn { 
         while(p<n) { p=p+1; buffer put(p); }
      }

      spawn { 
         var v: Int = _;
         while(c<n) { c=c+1; v = buffer.get; }
         cDone set true;
      }

      cDone.get;
      Console println(p + " " + c); 
   }


   private def toPositiveInt(s: Array[String]) = {
      val i = 
         try { Integer.parseInt(s(0)); } 
         catch { case _ => 1 }
      if (i>0) i; else 1;
   }
}


private class SharedBuffer() {
   var contents: Int = _;
   var available = false;

   def get = synchronized {
      while (available == false) wait();
      available = false;
         // Console println("\t" + "get " + contents);
      notifyAll();
      contents
   }

   def put(value: Int) = synchronized {
      while (available == true) wait();
      contents = value;
      available = true;
         // Console println("put " + value);
      notifyAll();
   }
}