How to run code in parallel?

前提是你 提交于 2019-12-14 03:47:43

问题


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

回答1:


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.




回答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 })
    // ...
}



回答3:


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)



来源:https://stackoverflow.com/questions/32718263/how-to-run-code-in-parallel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!