forked from scala/scala
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoneplacebuffer.scala
64 lines (51 loc) · 1.23 KB
/
oneplacebuffer.scala
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
package examples
object oneplacebuffer {
import scala.actors.Actor._
import scala.concurrent.ops
class OnePlaceBuffer {
private case class Put(x: Int)
private case object Get
private val m = actor {
var buf: Option[Int] = None
loop {
react {
case Put(x) if buf.isEmpty =>
println("put "+x);
buf = Some(x); reply()
case Get if !buf.isEmpty =>
val x = buf.get
println("get "+x)
buf = None; reply(x)
}
}
}
m.start()
def write(x: Int) { m !? Put(x) }
def read(): Int = (m !? Get).asInstanceOf[Int]
}
def kill(delay: Int) = new java.util.Timer().schedule(
new java.util.TimerTask {
override def run() {
println("[killed]")
sys exit 0
}
},
delay) // in milliseconds
def main(args: Array[String]) {
val buf = new OnePlaceBuffer
val random = new java.util.Random()
def producer(n: Int) {
Thread.sleep(random nextInt 1000)
buf write n
producer(n + 1)
}
def consumer {
Thread.sleep(random nextInt 1000)
val n = buf.read()
consumer
}
ops spawn producer(0)
ops spawn consumer
kill(10000)
}
}