Korzystanie z frameworku Scala actor jako obliczeń Fork-join?

Czy teoretycznie możliwe jest użycie Scala Actor Framework do wykonywania pewnego rodzaju asynchronicznych obliczeń dzielenia i podboju, podobnie jak framework Fork-Join JDK 7? Jeśli tak, to jak mogę wyrazić problem FJ z frameworkiem - np. samouczek łączy koncepcję? Urywki kodu są mile widziane.

(wpadłem na pomysł na podstawie resource video mam w moim drugim FJ związane pytanie .)

Author: Community, 2009-07-19

1 answers

Scala ma równoległość stylu FJ. Jest to call futures i jest częścią biblioteki aktorów

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)
}
Teraz do sedna pytania. Gdyby Scala nie miała futures to mógłbyś napisać sam na podstawie aktorów. W rzeczy samej. Wygląda mniej więcej tak.
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

}

I tak byś go używał

scala> val x = MyFuture(28 * 1000)
x: Foo.MyFuture[Int] = <function>

scala> x()
res4: Int = 28000
 33
Author: James Iry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-19 15:50:21