2011-03-24 64 views
2

我需要并行处理多个数据值(“SIMD”)。我可以使用java.util.concurrent的API(Executors.newFixedThreadPool())使用Future实例来处理在平行几个值:多个斯卡拉参与者服务于一项任务

import java.util.concurrent.{Executors, Callable} 

class ExecutorsTest { 
    private class Process(value: Int) 
     extends Callable[Int] { 
    def call(): Int = { 
     // Do some time-consuming task 
     value 
    } 
    } 

    val executorService = { 
    val threads = Runtime.getRuntime.availableProcessors 
    Executors.newFixedThreadPool(threads) 
    } 

    val processes = for (process <- 1 to 1000) yield new Process(process) 

    val futures = executorService.invokeAll(processes) 

    // Wait for futures 
} 

我该怎么做演员使用同样的事情?我不相信我想把所有的流程“喂”给一个演员,因为演员会按顺序执行它们。

我是否需要创建多个“处理器”参与者,并使用“调度员”参与者向每个“处理器”参与者发送相同数量的进程?

+0

我还在读“斯卡拉的演员”一书,并使用演员制作了一个玩具项目:http://www.scala-notes.org/2011/03/mandelactors/ – Jesper 2011-03-24 12:25:46

+0

@Jesper:我将添加您的博客到我的Instapaper队列稍后阅读。 – Ralph 2011-03-24 12:26:58

回答

10

如果您只是想要进行防火处理,为什么不使用Scala未来?

import scala.actors.Futures._ 
def example = { 
    val answers = (1 to 4).map(x => future { 
    Thread.sleep(x*1000) 
    println("Slept for "+x) 
    x 
    }) 
    val t0 = System.nanoTime 
    awaitAll(1000000,answers: _*) // Number is timeout in ms 
    val t1 = System.nanoTime 
    printf("%.3f seconds elapsed\n",(t1-t0)*1e-9) 
    answers.map(_()).sum 
} 

scala> example 
Slept for 1 
Slept for 2 
Slept for 3 
Slept for 4 
4.000 seconds elapsed 
res1: Int = 10 

基本上,所有你要做的就是把你想要一个future { }块中的代码,它会立即返回一个未来;应用它来获得答案(它会阻止,直到完成),或使用awaitAll超时等待,直到每个人都完成。


更新:从2.11开始,方法是用scala.concurrent.Future。上面的代码的翻译是:

import scala.concurrent._ 
import duration._ 
import ExecutionContext.Implicits.global 

def example = { 
    val answers = Future.sequence(
    (1 to 4).map(x => Future { 
     Thread.sleep(x*1000) 
     println("Slept for "+x) 
     x 
    }) 
) 
    val t0 = System.nanoTime 
    val completed = Await.result(answers, Duration(1000, SECONDS)) 
    val t1 = System.nanoTime 
    printf("%.3f seconds elapsed\n",(t1-t0)*1e-9) 
    completed.sum 
} 
+0

不错!我不知道斯卡拉期货。我正在(慢慢地)读“斯卡拉演员”的测试版,但还没有涉及到这一部分。我不记得描述未来的“Scala编程”(Odersky等)或“编程Scala”(Wampler和Payne)。 – Ralph 2011-03-24 12:03:33

+0

在这个例子中使用了多少个线程?如何配置它们?背景中是否有线程池? – 2011-03-24 12:06:33

+1

@ michael.kebe - 背景中有一个线程池。我之前没有配置过这个池的大小,所以我可能不应该对定制进行评论,以免我说错误。 – 2011-03-24 12:11:16