scala/ScalaBook/chapter-07/syncCell-v3.scala
import concurrent.MailBox
import concurrent.ops._
class cell (protected var contents : Int){
private val mbox = new MailBox
private case class Empty()
private case class Full(n : Int)
mbox send Full(contents) // initialize
def get() : Int =
mbox receive {
case Full(n) =>
mbox send Empty()
n
}
def set(n: Int) : Unit =
mbox receive {
case Empty() =>
mbox send Full(n)
}
}
object threadExample5 {
def main(args: Array[String]) {
var c = new cell(16)
spawn {
for ( i <- 1 to 10) {
var v = c.get
println("D---> got "+v)
c.set(2*v)
println("D---> send "+(2*v))
}
}
spawn {
var v = c.get
for ( i <- 1 to 10) {
c.set(v/2)
println("H---> send "+(v/2))
v = c.get
println("H---> got "+v)
}
}
}
}