lixiaojun
2023-04-12 fc6b7c9852f18e42fb9bccaf0cc22fbe5389d179
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// <copyright file="CommonParallel.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
 
using System;
using System.Collections.Generic;
 
#if !NETSTANDARD1_3
using System.Threading.Tasks;
using System.Collections.Concurrent;
#endif
 
namespace IStation.Numerics.Threading
{
    /// <summary>
    /// Used to simplify parallel code, particularly between the .NET 4.0 and Silverlight Code.
    /// </summary>
    internal static class CommonParallel
    {
        static ParallelOptions CreateParallelOptions()
        {
            return new ParallelOptions
            {
                MaxDegreeOfParallelism = Control.MaxDegreeOfParallelism,
                TaskScheduler = Control.TaskScheduler,
            };
        }
 
        /// <summary>
        /// Executes a for loop in which iterations may run in parallel.
        /// </summary>
        /// <param name="fromInclusive">The start index, inclusive.</param>
        /// <param name="toExclusive">The end index, exclusive.</param>
        /// <param name="body">The body to be invoked for each iteration range.</param>
        public static void For(int fromInclusive, int toExclusive, Action<int, int> body)
        {
            For(fromInclusive, toExclusive, Math.Max(1, (toExclusive - fromInclusive)/Control.MaxDegreeOfParallelism), body);
        }
 
        /// <summary>
        /// Executes a for loop in which iterations may run in parallel.
        /// </summary>
        /// <param name="fromInclusive">The start index, inclusive.</param>
        /// <param name="toExclusive">The end index, exclusive.</param>
        /// <param name="rangeSize">The partition size for splitting work into smaller pieces.</param>
        /// <param name="body">The body to be invoked for each iteration range.</param>
        public static void For(int fromInclusive, int toExclusive, int rangeSize, Action<int, int> body)
        {
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }
 
            if (fromInclusive < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(fromInclusive));
            }
 
            if (fromInclusive > toExclusive)
            {
                throw new ArgumentOutOfRangeException(nameof(toExclusive));
            }
 
            if (rangeSize < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(rangeSize));
            }
 
            var length = toExclusive - fromInclusive;
 
            // Special case: nothing to do
            if (length <= 0)
            {
                return;
            }
 
            // Special case: not worth to parallelize, inline
            if (Control.MaxDegreeOfParallelism < 2 || (rangeSize*2) > length)
            {
                body(fromInclusive, toExclusive);
                return;
            }
 
            // Common case
            Parallel.ForEach(
                Partitioner.Create(fromInclusive, toExclusive, rangeSize),
                CreateParallelOptions(),
                range => body(range.Item1, range.Item2));
        }
 
        /// <summary>
        /// Executes each of the provided actions inside a discrete, asynchronous task.
        /// </summary>
        /// <param name="actions">An array of actions to execute.</param>
        /// <exception cref="ArgumentException">The actions array contains a <c>null</c> element.</exception>
        /// <exception cref="AggregateException">At least one invocation of the actions threw an exception.</exception>
        public static void Invoke(params Action[] actions)
        {
            // Special case: no action
            if (actions.Length == 0)
            {
                return;
            }
 
            // Special case: single action, inline
            if (actions.Length == 1)
            {
                actions[0]();
                return;
            }
 
            // Special case: straight execution without parallelism
            if (Control.MaxDegreeOfParallelism < 2)
            {
                for (int i = 0; i < actions.Length; i++)
                {
                    actions[i]();
                }
 
                return;
            }
 
            // Common case
            Parallel.Invoke(
                CreateParallelOptions(),
                actions);
        }
 
        /// <summary>
        /// Selects an item (such as Max or Min).
        /// </summary>
        /// <param name="fromInclusive">Starting index of the loop.</param>
        /// <param name="toExclusive">Ending index of the loop</param>
        /// <param name="select">The function to select items over a subset.</param>
        /// <param name="reduce">The function to select the item of selection from the subsets.</param>
        /// <returns>The selected value.</returns>
        public static T Aggregate<T>(int fromInclusive, int toExclusive, Func<int, T> select, Func<T[], T> reduce)
        {
            if (select == null)
            {
                throw new ArgumentNullException(nameof(select));
            }
 
            if (reduce == null)
            {
                throw new ArgumentNullException(nameof(reduce));
            }
 
            // Special case: no action
            if (fromInclusive >= toExclusive)
            {
                return reduce(new T[0]);
            }
 
            // Special case: single action, inline
            if (fromInclusive == (toExclusive - 1))
            {
                return reduce(new[] { select(fromInclusive) });
            }
 
            // Special case: straight execution without parallelism
            if (Control.MaxDegreeOfParallelism < 2)
            {
                var mapped = new T[toExclusive - fromInclusive];
                for (int k = 0; k < mapped.Length; k++)
                {
                    mapped[k] = select(k + fromInclusive);
                }
 
                return reduce(mapped);
            }
 
            // Common case
            var intermediateResults = new List<T>();
            var syncLock = new object();
            Parallel.ForEach(
                Partitioner.Create(fromInclusive, toExclusive),
                CreateParallelOptions(),
                () => new List<T>(),
                (range, loop, localData) =>
                {
                    var mapped = new T[range.Item2 - range.Item1];
                    for (int k = 0; k < mapped.Length; k++)
                    {
                        mapped[k] = select(k + range.Item1);
                    }
 
                    localData.Add(reduce(mapped));
                    return localData;
                },
                localResult =>
                {
                    lock (syncLock)
                    {
                        intermediateResults.Add(reduce(localResult.ToArray()));
                    }
                });
            return reduce(intermediateResults.ToArray());
        }
 
        /// <summary>
        /// Selects an item (such as Max or Min).
        /// </summary>
        /// <param name="array">The array to iterate over.</param>
        /// <param name="select">The function to select items over a subset.</param>
        /// <param name="reduce">The function to select the item of selection from the subsets.</param>
        /// <returns>The selected value.</returns>
        public static TOut Aggregate<T, TOut>(T[] array, Func<int, T, TOut> select, Func<TOut[], TOut> reduce)
        {
            if (select == null)
            {
                throw new ArgumentNullException(nameof(select));
            }
 
            if (reduce == null)
            {
                throw new ArgumentNullException(nameof(reduce));
            }
 
            // Special case: no action
            if (array == null || array.Length == 0)
            {
                return reduce(new TOut[0]);
            }
 
            // Special case: single action, inline
            if (array.Length == 1)
            {
                return reduce(new[] { select(0, array[0]) });
            }
 
            // Special case: straight execution without parallelism
            if (Control.MaxDegreeOfParallelism < 2)
            {
                var mapped = new TOut[array.Length];
                for (int k = 0; k < mapped.Length; k++)
                {
                    mapped[k] = select(k, array[k]);
                }
 
                return reduce(mapped);
            }
 
            // Common case
            var intermediateResults = new List<TOut>();
            var syncLock = new object();
            Parallel.ForEach(
                Partitioner.Create(0, array.Length),
                CreateParallelOptions(),
                () => new List<TOut>(),
                (range, loop, localData) =>
                {
                    var mapped = new TOut[range.Item2 - range.Item1];
                    for (int k = 0; k < mapped.Length; k++)
                    {
                        mapped[k] = select(k + range.Item1, array[k + range.Item1]);
                    }
 
                    localData.Add(reduce(mapped));
                    return localData;
                },
                localResult =>
                {
                    lock (syncLock)
                    {
                        intermediateResults.Add(reduce(localResult.ToArray()));
                    }
                });
 
            return reduce(intermediateResults.ToArray());
        }
 
        /// <summary>
        /// Selects an item (such as Max or Min).
        /// </summary>
        /// <param name="fromInclusive">Starting index of the loop.</param>
        /// <param name="toExclusive">Ending index of the loop</param>
        /// <param name="select">The function to select items over a subset.</param>
        /// <param name="reducePair">The function to select the item of selection from the subsets.</param>
        /// <param name="reduceDefault">Default result of the reduce function on an empty set.</param>
        /// <returns>The selected value.</returns>
        public static T Aggregate<T>(int fromInclusive, int toExclusive, Func<int, T> select, Func<T, T, T> reducePair, T reduceDefault)
        {
            return Aggregate(fromInclusive, toExclusive, select, results =>
            {
                if (results == null || results.Length == 0)
                {
                    return reduceDefault;
                }
 
                if (results.Length == 1)
                {
                    return results[0];
                }
 
                T result = results[0];
                for (int i = 1; i < results.Length; i++)
                {
                    result = reducePair(result, results[i]);
                }
 
                return result;
            });
        }
 
        /// <summary>
        /// Selects an item (such as Max or Min).
        /// </summary>
        /// <param name="array">The array to iterate over.</param>
        /// <param name="select">The function to select items over a subset.</param>
        /// <param name="reducePair">The function to select the item of selection from the subsets.</param>
        /// <param name="reduceDefault">Default result of the reduce function on an empty set.</param>
        /// <returns>The selected value.</returns>
        public static TOut Aggregate<T, TOut>(T[] array, Func<int, T, TOut> select, Func<TOut, TOut, TOut> reducePair, TOut reduceDefault)
        {
            return Aggregate(array, select, results =>
            {
                if (results == null || results.Length == 0)
                {
                    return reduceDefault;
                }
 
                if (results.Length == 1)
                {
                    return results[0];
                }
 
                TOut result = results[0];
                for (int i = 1; i < results.Length; i++)
                {
                    result = reducePair(result, results[i]);
                }
 
                return result;
            });
        }
    }
}