Skip to content

Instantly share code, notes, and snippets.

@seadowg
Created May 20, 2012 16:02
Show Gist options
  • Save seadowg/2758608 to your computer and use it in GitHub Desktop.
Save seadowg/2758608 to your computer and use it in GitHub Desktop.
Producer/Consumer with Split Counting Semaphore in Scala
import actors.Actor._
val n = 8
val front = 0
val back = 0
val buffer = new Array[Int](n)
val full = new Semaphore(0)
val empty = new Semaphore(n)
// Producer
actor {
while (true) {
val produced = produce()
full.p()
buffer(back) = produced
back = (back + 1) % n
empty.v()
}
}.start()
// Consumer
actor {
while (true) {
empty.p()
val consumed = buffer(front)
front = (front + 1) % n
full.v()
workit(consumed)
}
}.start()
def produce() : Int = {
1
}
def workit(item: Int) {
println(item)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment