简单的Scala演员问题
问题描述:
我确定这是一个非常简单的问题,但不好意思说我无法理解:
I'm sure this is a very simple question, but embarrassed to say I can't get my head around it:
我在其中有一个值列表斯卡拉(Scala)。
我想使用actor并行地对每个值进行一些(外部)调用。
I have a list of values in Scala. I would like to use use actors to make some (external) calls with each value, in parallel.
我想等到所有值都被处理,然后继续。
I would like to wait until all values have been processed, and then proceed.
没有共享值被修改。
有人可以建议吗?
谢谢
答
Scala中有一个演员使用类,它是专门为这类问题:期货。可以这样解决这个问题:
There's an actor-using class in Scala that's made precisely for this kind of problem: Futures. This problem would be solved like this:
// This assigns futures that will execute in parallel
// In the example, the computation is performed by the "process" function
val tasks = list map (value => scala.actors.Futures.future { process(value) })
// The result of a future may be extracted with the apply() method, which
// will block if the result is not ready.
// Since we do want to block until all results are ready, we can call apply()
// directly instead of using a method such as Futures.awaitAll()
val results = tasks map (future => future.apply())
您去了。就是这样。