Search code examples
scalascala-2.8continuations

How to split and dispatch an async control-flow using Continuations?


I have an asynchronous control-flow like the following:

ActorA ! DoA(dataA, callback1, callbackOnErrorA)

def callback1() = {
  ...
  ActorB ! DoB(dataB, callback2, callbackOnErrorB)
}

def callback2() = {
  ActorC ! DoC(dataC, callback3, callbackOnErrorC)
} 

...

How would I divide this flow into several parts (continuations) and sequentially dispatch these to different actors (or threads/tasks) while maintaining the overall state?

Any hint appreciated, Thanks


Solution

  • This is very simplified, but shows how to split up a single control flow among three actors, passing the state along to each:

    package blevins.example
    
    import scala.continuations._
    import scala.continuations.ControlContext._
    import scala.actors.Actor._
    import scala.actors._
    
    object App extends Application {
    
      val actorA, actorB, actorC = actor {
        receive {
          case f: Function1[Unit,Unit] => { f() }
        }
      }
    
      def handle(a: Actor) = shift { k: (Unit=>Unit) =>
        a ! k
      }
    
      // Control flow to split up
      reset {
          // this is not handled by any actor
          var x = 1
          println("a: " + x)
    
          handle(actorA)  // actorA handles the below
          x += 4
          println("b: " + x)
    
          handle(actorB) // then, actorB handles the rest
          var y = 2
          x += 2
          println("c: " + x)
    
          handle(actorC) // and so on...
          y += 1
          println("d: " + x + ":" + y)
      }
    
    }