summaryrefslogtreecommitdiff
path: root/docs/examples/actors/BoundedBufferTest.scala
blob: 5a04f7aafd3b26a4879260f8e3af9e0116b0bed9 (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
package examples.actors

import scala.actors.Actor._

class BoundedBuffer[T](N: int) {
  private case class Get
  private case class Put(x: T)

  private val buffer = actor {
    val buf = new Array[T](N)
    var in = 0; var out = 0; var n = 0
    while(true) {
      receive {
        case Put(x) if n < N =>
          buf(in) = x; in = (in + 1) % N; n = n + 1; reply()
        case Get() if n > 0 =>
          val r = buf(out); out = (out + 1) % N; n = n - 1; reply(r)
      }
    }
  }

  def put(x: T): Unit = buffer !? Put(x)

  def get: T = (buffer !? Get()).asInstanceOf[T]
}

object BoundedBufferTest {
  def main(args: Array[String]) = {
    val buf = new BoundedBuffer[Int](1)
    buf.put(42)
    scala.Console.println("" + buf.get)
  }
}