8

我确信这是一个非常简单的问题,但不好意思说我无法理解它:

我在 Scala 中有一个值列表。我想使用使用演员对每个值进行一些(外部)调用,并行。

我想等到所有值都处理完毕,然后继续。

没有修改共享值。

有人可以建议吗?

谢谢

4

2 回答 2

17

Scala 中有一个actor-using 类就是专门针对这类问题而设计的:Futures。这个问题可以这样解决:

// 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())

你去吧。只是。

于 2010-04-02T04:50:38.383 回答
9

创建工人并要求他们使用!!; 然后读出结果(这些结果将被计算并在它们准备好时并行计算;然后您可以使用它们)。例如:

object Example {
  import scala.actors._
  class Worker extends Actor {
    def act() { Actor.loop { react {
      case s: String => reply(s.length)
      case _ => exit()
    }}}
  }
  def main(args: Array[String]) {
    val arguments = args.toList
    val workers = arguments.map(_ => (new Worker).start)
    val futures = for ((w,a) <- workers zip arguments) yield w !! a
    val results = futures.map(f => f() match {
      case i: Int => i
      case _ => throw new Exception("Whoops--didn't expect to get that!")
    })
    println(results)
    workers.foreach(_ ! None)
  }
}

这是一个非常便宜的计算——计算字符串的长度——但你可以在那里放一些昂贵的东西来确保它确实并行发生(act 块的最后一件事应该是回复答案) . 请注意,我们还包括一个工人关闭自己的案例,当我们都完成后,我们告诉工人关闭。(在这种情况下,任何非字符串都会关闭工作程序。)

我们可以尝试一下以确保它有效:

scala> Example.main(Array("This","is","a","test"))
List(4, 2, 1, 4)
于 2010-04-02T03:40:48.393 回答