Advertisement
Guest User

Untitled

a guest
Mar 7th, 2014
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.35 KB | None | 0 0
  1.     class Channel[T]
  2.     {
  3.         abstract class State
  4.         case class Request() extends State
  5.         case class Offer(t : T) extends State
  6.         case class Answered(t : T) extends State
  7.         case class Idle() extends State
  8.  
  9.         protected var state : State = Idle()
  10.  
  11.         def put(msg : T) : Unit =
  12.         {
  13.             this.synchronized
  14.             {
  15.                 state match {
  16.  
  17.                     case Request() =>
  18.                         state = Answered(msg)
  19.                         notifyAll
  20.  
  21.                     case _ =>
  22.                         waitFor(state == Idle())
  23.                         state = Offer(msg)
  24.                         notifyAll
  25.                         waitFor(state == Idle())
  26.                         notifyAll
  27.                 }
  28.             }
  29.         }
  30.  
  31.         def get() : T =
  32.         {
  33.             this.synchronized
  34.             {
  35.                 state match {
  36.  
  37.                     case Offer(t) =>
  38.                         val ret = t
  39.                         state = Idle()
  40.                         notifyAll
  41.                         return ret
  42.  
  43.                     case _ =>
  44.                         waitFor(state == Idle())
  45.                         state = Request()
  46.                         notifyAll
  47.                         waitFor(cond(state) { case Answered(m) => true })
  48.                         state match {
  49.                             case Answered(t) => return t
  50.                             case _ => assert(false).asInstanceOf[T]
  51.                         }
  52.                        
  53.                 }
  54.                
  55.             }
  56.         }
  57.  
  58.         private def waitFor(b : => Boolean) =
  59.             while(!b) wait
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement