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
+4
source share
3 answers

You can use standard .NET tasks for this - there are no special F # functions or special syntax for spawning computations 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 yours Seq.map2to Array.map2- computing on sequences is lazy, and so running them inside a task actually did nothing. With arrays, the entire calculation completes immediately.

+7
source

, , , Async, :

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)
        }

:

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 })
    // ...
}
+2

try Array.zipu Array.Parallel.map?

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

or just use ParallelSeq(see http://fsprojects.imtqy.com/FSharp.Collections.ParallelSeq/ for more information)

+1
source

Source: https://habr.com/ru/post/1608489/


All Articles