4

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
asked Sep 22, 2015 at 13:30

3 Answers 3

7

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.

answered Sep 22, 2015 at 14:13
Sign up to request clarification or add additional context in comments.

2 Comments

is it a1 = a1Work.Value or a1 = a1Work.Result
if there is another loop let c1=Seq.map2 (fun a b->a/b) c2 c3 do i need to set it as task as well?
2

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 })
 // ...
}
answered Sep 22, 2015 at 14:29

Comments

1

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)

answered Sep 22, 2015 at 14:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.