Created
May 20, 2012 16:02
-
-
Save seadowg/2758608 to your computer and use it in GitHub Desktop.
Producer/Consumer with Split Counting Semaphore in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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