Are F # Async.Parallel results guaranteed in order?

Have results been received from F # Async. Parallel operation guaranteed for admission to order assignments? My sample code returns the results in order, but I cannot find mention in the MSDN docs or the F # specification, guaranteeing this must , that it is not a coincidence.

Here is my sample code:

let r = System.Random() Async.Parallel [ for i in 0..10 -> async { let rand_num = r.Next(10) do! Async.Sleep(rand_num) (* Simulate jobs taking a variable amount of time *) printfn "%i %i" i rand_num return i } ] |> Async.RunSynchronously |> printfn "%A" 

And here is the conclusion.

 0 0 5 1 4 1 3 3 10 6 9 4 7 5 2 5 1 5 8 7 6 9 [|0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10|] 

You can see that async functions end in an undefined order on this run, but the resulting array is sorted. Is this behavior guaranteed?

+6
source share
1 answer

At the moment, the source of the function is recorded so that this guarantee is respected. Looking at control.fs around line # 1300 for definition, we can see that the function that puts the results in the output array is

 let recordSuccess i res = results.[i] <- res; finishTask(Interlocked.Decrement count) 

this function is called in this segment

  tasks |> Array.iteri (fun ip -> queueAsync innerCTS.Token // on success, record the result (fun res -> recordSuccess i res) 

where tasks has the original tasks in sorted order. This ensures that the output list is in the same order as the input.

UPDATE

The specification, at least, implies that the order is fixed - it contains this code:

 let rec fib x = if x < 2 then 1 else fib(x-1) + fib(x-2) let fibs = Async.Parallel [ for i in 0..40 -> async { return fib(i) } ] |> Async.RunSynchronously printfn "The Fibonacci numbers are %A" fibs //I changed this line to be accurate System.Console.ReadKey(true) 

If the specification did not guarantee the order of output, this code would be incorrect.

+11
source

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


All Articles