Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import akka.actor._
- object Fork {
- def props(id: Int): Props = Props(new Fork(id))
- final case class Take(philosopher: Int)
- final case class Release(philosopher: Int)
- final case class TookFork(fork: Int)
- final case class ReleasedFork(fork: Int)
- }
- class Fork(val id: Int) extends Actor {
- import Fork._
- object Status extends Enumeration {
- val FREE, TAKEN = Value
- }
- private var _status: Status.Value = Status.FREE
- private var _held_by: Int = -1
- def receive = {
- case Take(philosopher) if _status == Status.FREE => {
- println(s"tPhilosopher $philosopher takes fork $id.")
- take(philosopher)
- sender() ! TookFork(id)
- context.become(taken, false)
- }
- case Release(philosopher) if _status == Status.TAKEN && _held_by == philosopher => {
- println(s"tPhilosopher $philosopher puts down fork $id.")
- release()
- sender() ! ReleasedFork(id)
- context.unbecome()
- }
- }
- def take(philosopher: Int) = {
- _status = Status.TAKEN
- _held_by = philosopher
- }
- def release() = {
- _status = Status.FREE
- _held_by = -1
- }
- }
- override def unhandled(message: Any): Unit = {
- self forward message
- }
Add Comment
Please, Sign In to add comment