简单的Scala演员问题

7za*_*rk7 8 scala actor

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

我在Scala中有一个值列表.我想使用use actors与每个值并行地进行一些(外部)调用.

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

没有修改共享值.

有人可以建议吗?

谢谢

Dan*_*ral 17

Scala中有一个演员使用的类,它正是针对这类问题制作的:期货.这个问题会像这样解决:

// 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())
Run Code Online (Sandbox Code Playgroud)

你去吧 只是.


Rex*_*err 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)
  }
}
Run Code Online (Sandbox Code Playgroud)

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

我们可以尝试这一点,以确保它的工作原理:

scala> Example.main(Array("This","is","a","test"))
List(4, 2, 1, 4)
Run Code Online (Sandbox Code Playgroud)