blob: 55d85068ad288e3033cdd3ac7606cd4a3d3dc93a (
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
|
package examples
object oneplacebuffer {
import scala.concurrent._
class OnePlaceBuffer {
private val m = new MailBox() {} // An internal mailbox
private case class Empty() // Types of messages we deal with
private case class Full(x: Int)
m send Empty() // Initialization
def write(x: Int): Unit = m receive {
case Empty() =>
Console.println("put " + x)
m send Full(x)
}
def read: Int = m receive {
case Full(x) =>
Console.println("get " + x)
m send Empty(); x
}
}
def kill(delay: Int) = new java.util.Timer().schedule(
new java.util.TimerTask {
override def run() = {
Console.println("[killed]")
System.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)
}
}
|