Example17.3

「Example17.3」の編集履歴(バックアップ)一覧に戻る
Example17.3」を以下のとおり復元します。
#co(){
17.4 Parallel Computations

The next example presents a function par which takes a pair of computations as parameters and which returns the results of the computations in another pair. The two computations are performed in parallel.

The function is defined in object scala.concurrent.ops as follows.
}

** 17.4 並列計算

次の例では、関数 par は計算のペアを引数としてとり、計算結果を別のペアで返します。2つの計算は並列実行されます。

この関数はオブジェクト scala.concurrent.ops において、次のように定義されています。

      def par[A, B](xp: => A, yp: => B): (A, B) = {
        val y = new SyncVar[B]
        spawn { y set yp }
        (xp, y.get)
      }

#co(){
Defined in the same place is a function replicate which performs a number ofreplicates of a computation in parallel. Each replication instance is passed an integer number which identifies it.
}

同じ場所で replicate 関数が定義されていて、多数の計算の複製を並列実行しま
す。各複製インスタンスには、それを識別する整数値が渡されます。

  def replicate(start: Int, end: Int)(p: Int => Unit) {
    if (start == end)
      ()
    else if (start + 1 == end)
      p(start)
    else {
      val mid = (start + end) / 2
      spawn { replicate(start, mid)(p) }
      replicate(mid, end)(p)
    }
  }

#co(){
The next function uses replicate to perform parallel computations on all elements of an array.
}

次の関数は、配列のすべての要素について並列計算を実行するために、replicate を使っています。

  def parMap[A,B](f: A => B, xs: Array[A]): Array[B] = {
    val results = new Array[B](xs.length)
    replicate(0, xs.length) { i => results(i) = f(xs(i)) }
    results
  }

#center(){[[前ページ>Example17.3]] [[ 17 章>Chapter 17 Abstractions for Concurrency]] [[目次>ScalaByExample和訳]] [[次ページ>Example17.5]]}

----
#comment

復元してよろしいですか?

ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。