假设我有睡眠功能:
def sleep(delay:Int) : Unit @suspendable = {
....
}
是否可以使用函数future来创建可以同步等待的睡眠函数的异步版本。
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
答案 0 :(得分:2)
object Forks {
import scala.util.continuations._
case class Forker(forks: Vector[() => Unit @suspendable]) {
def ~(block: => Unit @suspendable): Forker = Forker(forks :+ (() => block))
def joinIf(pred: Int => Boolean): Unit @suspendable = shift { k: (Unit => Unit) =>
val counter = new java.util.concurrent.atomic.AtomicInteger(forks.size)
forks foreach { f =>
reset {
f()
if (pred(counter.decrementAndGet)) k()
}
}
}
def joinAll() = joinIf(_ == 0)
def joinAny() = joinIf(_ == forks.size - 1)
}
def fork(block: => Unit @suspendable): Forker = Forker(Vector(() => block))
}
使用fork(),我们现在可以等待许多“suspendables”。使用〜()将suspendables链接在一起。使用joinAll()等待所有suspendables和joinAny()等待只有一个。使用joinIf()来自定义连接策略。
object Tests extends App {
import java.util.{Timer, TimerTask}
import scala.util.continuations._
implicit val timer = new Timer
def sleep(ms: Int)(implicit timer: Timer): Unit @suspendable = {
shift { k: (Unit => Unit) =>
timer.schedule(new TimerTask {
def run = k()
}, ms)
}
}
import Forks._
reset {
fork {
println("sleeping for 2000 ms")
sleep(2000)
println("slept for 2000 ms")
} ~ {
println("sleeping for 4000 ms")
sleep(4000)
println("slept for 4000 ms")
} joinAll()
println("and we are done")
}
println("outside reset")
readLine
timer.cancel
}
这是输出。程序从时间T开始:
sleeping for 2000 ms
sleeping for 4000 ms
outside reset <<<<<< T + 0 second
slept for 2000 ms <<<<<< T + 2 seconds
slept for 4000 ms <<<<<< T + 4 seconds
and we are done <<<<<< T + 4 seconds
答案 1 :(得分:1)
我不确定我是否完全理解这个问题,但这是一次尝试:
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
}
}
此处,Future
实例仅仅是Thread
上的句柄,因此您可以使用其join
方法进行阻止,直至完成。
future
函数采用类型A => B
的函数,并返回一个函数,当提供A
时,该函数将启动线程以运行“futured”函数,并且将其包装在Future
中,然后将其注入连续符,从而将其分配给val future1
。
这是否与您的目标相近?