Skip to content

Instantly share code, notes, and snippets.

@toluju
Created January 18, 2011 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save toluju/785100 to your computer and use it in GitHub Desktop.
Save toluju/785100 to your computer and use it in GitHub Desktop.
A better scala barbershop simulator.
import scala.actors.Actor
import scala.actors.Actor._
import scala.util.Random
import scala.collection.{immutable, mutable}
val rand = new Random()
case class Customer(id: Int) {
var shorn:Boolean = false
}
case class RequestCustomer()
val shop = actor {
val seats = 3
val queue = new mutable.SynchronizedQueue[Customer]()
println("(s) the shop is open")
loop { react {
case customer: Customer =>
println("(c) %d entering shop" format customer.id)
if (seats < queue.size)
println("(s) turning away customer %d" format customer.id)
else
queue enqueue customer
case request: RequestCustomer =>
if (queue.isEmpty)
continue
else
reply(queue.dequeue)
}}
}
val barber = actor { loop {
Thread.sleep(100 + rand.nextInt(400))
shop !? RequestCustomer() match {
case customer: Customer =>
println("(b) cutting hair of customer %d" format customer.id)
customer.shorn = true
}
}}
// customers arrive at random intervals
val customers = (1 to 20) map { i =>
val customer = new Customer(i)
shop ! customer
Thread.sleep(rand.nextInt(450))
customer
}
// wait for any remaining concurrent actions to complete
Thread.sleep(2000)
val shornCount = customers.filter(_.shorn).size
println("[!] " + shornCount + " customers got haircuts today")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment