ben*_*phy 12 continuations scala
假设我有睡眠功能:
def sleep(delay:Int) : Unit @suspendable = {
....
}
Run Code Online (Sandbox Code Playgroud)
是否有可能有一个函数future来创建一个可以同步等待的睡眠函数的异步版本.
def future(targetFunc: (Int => Unit @suspendable)) : (Int => Future) = {
....
}
class Future {
def await : Unit @suspendable = {
....
}
}
Run Code Online (Sandbox Code Playgroud)
你应该能够做这样的事情:
reset {
val sleepAsync = future(sleep)
val future1 = sleepAsync(2000)
val future2 = sleepAsync(3000)
future1.await
future2.await
/* finishes after a delay of 3000 */
}
Run Code Online (Sandbox Code Playgroud)
对sleepAsync的两次调用应该会立即返回,而对Future#await的两次调用应该会阻塞.当然它们都会在重置结束时掉线,后面的代码负责在延迟后调用延续.
否则是否有另一种方法可以并行运行两个@suspendable函数并等待它们完成?
我有一个可编辑的要点与我想做的骨架:https://gist.github.com/1191381
我不确定我是否完全理解这个问题,但可以尝试一下:
import scala.util.continuations._
class Future(thread: Thread) {
def await = thread.join
}
object Future {
def sleep(delay: Long) = Thread.sleep(delay)
def future[A,B](f: A => B) = (a: A) => shift { k: (Future => Unit) =>
val thread = new Thread { override def run() { f(a) } }
thread.start()
k(new Future(thread))
}
def main(args:Array[String]) = reset {
val sleepAsync = future(sleep)
val future1 = sleepAsync(2000) // returns right away
val future2 = sleepAsync(3000) // returns right away
future1.await // returns after two seconds
future2.await // returns after an additional one second
// finished after a total delay of three seconds
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,Future实例只不过是 a 的句柄Thread,因此您可以使用它的join方法来阻塞,直到它完成。
该future函数接受一个 类型的函数A => B,并返回一个函数,当提供 an 时,该函数A将启动一个线程来运行“未来”函数,并将其包装在 a 中Future,该函数被注入回延续中,从而将其分配给val future1。
这与您想要的接近吗?