diff options
author | michelou <michelou@epfl.ch> | 2011-11-23 18:26:50 +0000 |
---|---|---|
committer | michelou <michelou@epfl.ch> | 2011-11-23 18:26:50 +0000 |
commit | 4213eb4d56c51311bcd2ccaa9710897aaef974de (patch) | |
tree | c431f982ecbf80bb54670e3294b752b1e4043bcb /docs/examples/oneplacebuffer.scala | |
parent | 667227b796fb2601363b6b7c0763b0e739a0edb2 (diff) | |
download | scala-4213eb4d56c51311bcd2ccaa9710897aaef974de.tar.gz scala-4213eb4d56c51311bcd2ccaa9710897aaef974de.tar.bz2 scala-4213eb4d56c51311bcd2ccaa9710897aaef974de.zip |
updated some code examples
Diffstat (limited to 'docs/examples/oneplacebuffer.scala')
-rw-r--r-- | docs/examples/oneplacebuffer.scala | 52 |
1 files changed, 28 insertions, 24 deletions
diff --git a/docs/examples/oneplacebuffer.scala b/docs/examples/oneplacebuffer.scala index 02b8a9cec6..f7047a1c92 100644 --- a/docs/examples/oneplacebuffer.scala +++ b/docs/examples/oneplacebuffer.scala @@ -2,35 +2,39 @@ package examples object oneplacebuffer { - import scala.concurrent.{MailBox, ops} + import scala.actors.Actor._ + import scala.concurrent.ops 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) + private case class Put(x: Int) + private case object Get - m send Empty() // Initialization - - def write(x: Int) { - m receive { - case Empty() => - println("put " + x) - m send Full(x) + 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 read: Int = m receive { - case Full(x) => - println("get " + x) - m send Empty(); x - } + 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() = { + override def run() { println("[killed]") - exit(0) + sys exit 0 } }, delay) // in milliseconds @@ -40,19 +44,19 @@ object oneplacebuffer { val random = new java.util.Random() def producer(n: Int) { - Thread.sleep(random.nextInt(1000)) - buf.write(n) + Thread.sleep(random nextInt 1000) + buf write n producer(n + 1) } def consumer { - Thread.sleep(random.nextInt(1000)) - val n = buf.read + Thread.sleep(random nextInt 1000) + val n = buf.read() consumer } - ops.spawn(producer(0)) - ops.spawn(consumer) + ops spawn producer(0) + ops spawn consumer kill(10000) } |