Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Channel[T]
- {
- abstract class State
- case class Request() extends State
- case class Offer(t : T) extends State
- case class Answered(t : T) extends State
- case class Idle() extends State
- protected var state : State = Idle()
- def put(msg : T) : Unit =
- {
- this.synchronized
- {
- state match {
- case Request() =>
- state = Answered(msg)
- notifyAll
- case _ =>
- waitFor(state == Idle())
- state = Offer(msg)
- notifyAll
- waitFor(state == Idle())
- notifyAll
- }
- }
- }
- def get() : T =
- {
- this.synchronized
- {
- state match {
- case Offer(t) =>
- val ret = t
- state = Idle()
- notifyAll
- return ret
- case _ =>
- waitFor(state == Idle())
- state = Request()
- notifyAll
- waitFor(cond(state) { case Answered(m) => true })
- state match {
- case Answered(t) => return t
- case _ => assert(false).asInstanceOf[T]
- }
- }
- }
- }
- private def waitFor(b : => Boolean) =
- while(!b) wait
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement