【发布时间】:2011-11-09 18:58:13
【问题描述】:
假设我有一个睡眠功能:
def sleep(delay:Int) : Unit @suspendable = {
....
}
是否有可能有一个函数 future 来创建可以同步等待的 sleep 函数的异步版本。
def future(targetFunc: (Int => Unit @suspendable)) : (Int => Future) = {
....
}
class Future {
def await : Unit @suspendable = {
....
}
}
你应该可以这样做:
reset {
val sleepAsync = future(sleep)
val future1 = sleepAsync(2000)
val future2 = sleepAsync(3000)
future1.await
future2.await
/* finishes after a delay of 3000 */
}
对 sleepAsync 的两次调用应该会立即返回,对 Future#await 的两次调用应该会出现阻塞。当然,它们都真正脱离了重置的结束,并且之后的代码负责在延迟后调用延续。
否则是否有替代方法可以并行运行两个@suspendable 函数并等待它们完成?
我有一个可编译的要点,其中包含我想做的事情的骨架:https://gist.github.com/1191381
【问题讨论】:
-
我写了这个:gist.github.com/1191571 这似乎可行,但似乎相当复杂。我觉得我可能错过了一种更简单的方法。
-
还发现了这个:days2011.scala-lang.org/node/138/288 这似乎做得更好。
-
你对“获胜”的答案有偏好吗?我需要发放赏金。
标签: scala continuations