HaagenDaz
HaagenDaz

Reputation: 461

How to run code in parallel?

How can i run these two independent loops simultaneously in parallel.

let a1=Seq.map2 (fun a b->(1.0-a)/(a-b)) a2  a3

let b1=Seq.map2 (fun a b->a*b) b2 b3

Upvotes: 4

Views: 856

Answers (3)

Tarmil
Tarmil

Reputation: 11362

If this is a pattern you find yourself using regularly, it could be useful to write a generic function that runs two Async computations in parallel, for example like this:

module Async =

    let Parallel2 (a: Async<'T>) (b: Async<'U>) : Async<'T * 'U> =
        async {
            let! res =
                Async.Parallel [|
                    async { let! a = a in return box a }
                    async { let! b = b in return box b }
                |]
            return (res.[0] :?> 'T, res.[1] :?> 'U)
        }

You can then use it like so:

async {
    let! a1, b1 =
        Async.Parallel2
            (async { return Array.map2 (fun a b->(1.0-a)/(a-b)) a2 a3 })
            (async { return Array.map2 (fun a b->a*b) b2 b3 })
    // ...
}

Upvotes: 2

fairjm
fairjm

Reputation: 1187

try Array.zip and Array.Parallel.map?

Array.zip [|1;2;3|] [|2;3;4|] |> Array.Parallel.map (fun (a,b) -> a + b)

or simply use the ParallelSeq(see http://fsprojects.github.io/FSharp.Collections.ParallelSeq/ for more information)

Upvotes: 1

Tomas Petricek
Tomas Petricek

Reputation: 243041

You can use standard .NET tasks for this - there are no special F# functions or special syntax for spawning a computation in the background:

let a1Work = Task.Factory.StartNew(fun () ->
  Array.map2 (fun a b->(1.0-a)/(a-b)) a2  a3)
let b1 = Array.map2 (fun a b->a*b) b2 b3
let a1 = a1Work.Value

I also changed your Seq.map2 to Array.map2 - computations on sequences are lazy and so running them inside a task would not actually do anything. With arrays, the whole calculation is completed immediately.

Upvotes: 7

Related Questions