2011-03-24 40 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