This repository has been archived by the owner on Apr 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParallelAlgorithms_SpeculativeFor.cs
59 lines (53 loc) · 2.85 KB
/
ParallelAlgorithms_SpeculativeFor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//--------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: ParallelAlgorithms_SpeculativeFor.cs
//
//--------------------------------------------------------------------------
using System.Collections.Generic;
using System.Threading.Tasks;
namespace System.Threading.Algorithms
{
public static partial class ParallelAlgorithms
{
/// <summary>Executes a function for each value in a range, returning the first result achieved and ceasing execution.</summary>
/// <typeparam name="TResult">The type of the data returned.</typeparam>
/// <param name="fromInclusive">The start of the range, inclusive.</param>
/// <param name="toExclusive">The end of the range, exclusive.</param>
/// <param name="options">The options to use for processing the loop.</param>
/// <param name="body">The function to execute for each element.</param>
/// <returns>The result computed.</returns>
public static TResult SpeculativeFor<TResult>(
int fromInclusive, int toExclusive, Func<int, TResult> body)
{
return SpeculativeFor(fromInclusive, toExclusive, s_defaultParallelOptions, body);
}
/// <summary>Executes a function for each value in a range, returning the first result achieved and ceasing execution.</summary>
/// <typeparam name="TResult">The type of the data returned.</typeparam>
/// <param name="fromInclusive">The start of the range, inclusive.</param>
/// <param name="toExclusive">The end of the range, exclusive.</param>
/// <param name="options">The options to use for processing the loop.</param>
/// <param name="body">The function to execute for each element.</param>
/// <returns>The result computed.</returns>
public static TResult SpeculativeFor<TResult>(
int fromInclusive, int toExclusive, ParallelOptions options, Func<int, TResult> body)
{
// Validate parameters; the Parallel.For we delegate to will validate the rest
if (body == null) throw new ArgumentNullException("body");
// Store one result. We box it if it's a value type to avoid torn writes and enable
// CompareExchange even for value types.
object result = null;
// Run all bodies in parallel, stopping as soon as one has completed.
Parallel.For(fromInclusive, toExclusive, options, (i, loopState) =>
{
// Run an iteration. When it completes, store (box)
// the result, and cancel the rest
Interlocked.CompareExchange(ref result, (object)body(i), null);
loopState.Stop();
});
// Return the computed result
return (TResult)result;
}
}
}