我正在尝试在Scala中实现一个简单的并行列表和。下面这个使用递归分治,但事实证明程序没有终止。问题出在哪儿?这种计算的正确方法是什么?
import java.util.concurrent.{Callable, ExecutorService, Executors, Future}
val es=Executors.newWorkStealingPool()
def sumP(ints: IndexedSeq[Int]): Int = {if (ints.size <= 1)
ints.headOption getOrElse 0 else {
val (l, r) = ints.splitAt(ints.length / 2)
val fut_l = es.submit(new Callable[Int] {
override def call = sumP(l)
})
val fut_r = es.submit(new Callable[Int] {
override def call = sumP(r)
})
fut_l.get() + fut_r.get()
}}
println("result is here: ")
val res=sumP(1 to 4000000)
答案 0 :(得分:2)
这应该快得多。
import java.util.concurrent.{Callable, Executors}
val es=Executors.newWorkStealingPool()
def sumP(ints: IndexedSeq[Int], threadLimit: Int = 8): Int = {
if (ints.size < 5 || threadLimit < 2) ints.sum
else {
val (l, r) = ints.splitAt(ints.length / 2)
es.submit(new Callable[Int] {override def call = sumP(l, threadLimit/2)})
.get() +
es.submit(new Callable[Int] {override def call = sumP(r, threadLimit/2)})
.get()
}
}
sumP(1 to 40000) //res0: Int = 800020000
与您的代码几乎相同,但并行化的数量,即线程数,有限。 (代码也更容易查看。)