스칼라는 FJ 스타일의 병렬 처리를 가지고있다. 외침 선물이고 배우 도서관의 일부입니다.
import scala.actors.Future
import scala.actors.Futures._
def mergeSort[A <% Ordered[A]](xs : List[A]) : List[A] = {
// merge is not interesting, it's sequential. The complexity lies in keeping it tail recursive
def merge[A <% Ordered[A]](accum : List[A], left : List[A], right : List[A]) : List[A] = {
(left, right) match {
case (lhead::ltail, rhead::rtail) =>
if (lhead <= rhead) merge(lhead :: accum, ltail, right)
else merge(rhead :: accum, left, rtail)
case (Nil, _) => accum reverse_::: right
case _ => accum reverse_::: left
}
}
// here's the parallel sort bit
def sort[A <% Ordered[A]](xs : List[A], length : Int) : List[A] = {
if (length <= 1) xs
else {
val leftLength = length/2
val rightLength = length - leftLength
val (left, right) = xs splitAt leftLength
// fork
val leftFork = future { sort(left, leftLength) }
val rightFork = future { sort(right, rightLength) }
// join
val leftJoin = leftFork()
val rightJoin = rightFork()
// merge
merge(Nil, leftJoin, rightJoin)
}
}
sort(xs, xs.length)
}
지금, 질문의 핵심입니다. 스칼라에 선물이 없다면 액터를 기반으로 자신을 쓸 수 있습니까? 과연. 이것은 다소 비슷하게 보일 것입니다.
import scala.actors.Actor
import scala.actors.Actor._
object MyFuture {
def apply[T](x : => T) : MyFuture[T] = {
val future = new MyFuture[T]
val act = actor {
react {
case sender : Actor => sender ! (future, x)
}
}
act ! self
future
}
}
class MyFuture[A] extends Function0[A] {
me =>
lazy val result = receive {
case (`me`, result) => result.asInstanceOf[A]
}
def apply() = result
}
그리고 당신이 그렇게
scala> val x = MyFuture(28 * 1000)
x: Foo.MyFuture[Int] = <function>
scala> x()
res4: Int = 28000
와우처럼 사용하는 것입니다, 감사합니다. – akarnokd
크기 400의 목록으로 FJ 예제를 시도했지만 CPU로드가 거의 들지 않습니다 (모든 코어에 100 %가되어야합니다). 그걸 설명하면 어떨까요? – awk
이것을 어떻게 scala 2.10으로 재 작성하여 future() 차단을 사용하지 못하게 할 수 있습니까? – yura