Guest User

Untitled

a guest
Dec 19th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. import akka.actor._
  2.  
  3. object Fork {
  4. def props(id: Int): Props = Props(new Fork(id))
  5. final case class Take(philosopher: Int)
  6. final case class Release(philosopher: Int)
  7. final case class TookFork(fork: Int)
  8. final case class ReleasedFork(fork: Int)
  9. }
  10.  
  11. class Fork(val id: Int) extends Actor {
  12. import Fork._
  13.  
  14. object Status extends Enumeration {
  15. val FREE, TAKEN = Value
  16. }
  17.  
  18. private var _status: Status.Value = Status.FREE
  19. private var _held_by: Int = -1
  20.  
  21. def receive = {
  22. case Take(philosopher) if _status == Status.FREE => {
  23. println(s"tPhilosopher $philosopher takes fork $id.")
  24. take(philosopher)
  25. sender() ! TookFork(id)
  26. context.become(taken, false)
  27. }
  28. case Release(philosopher) if _status == Status.TAKEN && _held_by == philosopher => {
  29. println(s"tPhilosopher $philosopher puts down fork $id.")
  30. release()
  31. sender() ! ReleasedFork(id)
  32. context.unbecome()
  33. }
  34. }
  35.  
  36. def take(philosopher: Int) = {
  37. _status = Status.TAKEN
  38. _held_by = philosopher
  39. }
  40.  
  41. def release() = {
  42. _status = Status.FREE
  43. _held_by = -1
  44. }
  45. }
  46.  
  47. override def unhandled(message: Any): Unit = {
  48. self forward message
  49. }
Add Comment
Please, Sign In to add comment