3 // Copyright (c) 2008 Jérémie "Garuma" Laval
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 using System.Collections.Generic;
28 using System.Collections.Concurrent;
29 using System.Threading;
30 using System.Runtime.InteropServices;
32 namespace System.Threading.Tasks
34 public static class Parallel
36 #if MOONLIGHT || MOBILE
37 static readonly bool sixtyfour = IntPtr.Size == 8;
39 static readonly bool sixtyfour = Environment.Is64BitProcess;
42 internal static int GetBestWorkerNumber ()
44 return GetBestWorkerNumber (TaskScheduler.Current);
47 internal static int GetBestWorkerNumber (TaskScheduler scheduler)
49 return scheduler.MaximumConcurrencyLevel;
52 static int GetBestWorkerNumber (int from, int to, ParallelOptions options, out int step)
54 int num = Math.Min (GetBestWorkerNumber (options.TaskScheduler),
55 options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
56 // Integer range that each task process
57 if ((step = (to - from) / num) < 5) {
59 num = (to - from) / 5;
67 static void HandleExceptions (IEnumerable<Task> tasks)
69 HandleExceptions (tasks, null);
72 static void HandleExceptions (IEnumerable<Task> tasks, ParallelLoopState.ExternalInfos infos)
74 List<Exception> exs = new List<Exception> ();
75 foreach (Task t in tasks) {
76 if (t.Exception != null)
77 exs.Add (t.Exception);
82 infos.IsExceptional = true;
84 throw new AggregateException (exs);
88 static void InitTasks (Task[] tasks, int count, Action action, ParallelOptions options)
90 TaskCreationOptions creation = TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
92 for (int i = 0; i < count; i++) {
94 tasks [i] = Task.Factory.StartNew (action, creation);
96 tasks [i] = Task.Factory.StartNew (action, options.CancellationToken, creation, options.TaskScheduler);
102 public static ParallelLoopResult For (int fromInclusive, int toExclusive, Action<int> body)
104 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
107 public static ParallelLoopResult For (int fromInclusive, int toExclusive, Action<int, ParallelLoopState> body)
109 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
112 public static ParallelLoopResult For (int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int> body)
114 return For (fromInclusive, toExclusive, parallelOptions, (index, state) => body (index));
117 public static ParallelLoopResult For (int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int, ParallelLoopState> body)
119 return For<object> (fromInclusive, toExclusive, parallelOptions, () => null, (i, s, l) => { body (i, s); return null; }, _ => {});
122 public static ParallelLoopResult For<TLocal> (int fromInclusive,
124 Func<TLocal> localInit,
125 Func<int, ParallelLoopState, TLocal, TLocal> body,
126 Action<TLocal> localFinally)
128 return For<TLocal> (fromInclusive, toExclusive, ParallelOptions.Default, localInit, body, localFinally);
131 public static ParallelLoopResult For<TLocal> (int fromInclusive,
133 ParallelOptions parallelOptions,
134 Func<TLocal> localInit,
135 Func<int, ParallelLoopState, TLocal, TLocal> body,
136 Action<TLocal> localFinally)
139 throw new ArgumentNullException ("body");
140 if (localInit == null)
141 throw new ArgumentNullException ("localInit");
142 if (localFinally == null)
143 throw new ArgumentNullException ("localFinally");
144 if (parallelOptions == null)
145 throw new ArgumentNullException ("options");
146 if (fromInclusive >= toExclusive)
147 return new ParallelLoopResult (null, true);
149 // Number of task toExclusive be launched (normally == Env.ProcessorCount)
151 int num = GetBestWorkerNumber (fromInclusive, toExclusive, parallelOptions, out step);
153 Task[] tasks = new Task [num];
155 StealRange[] ranges = new StealRange[num];
156 for (int i = 0; i < num; i++)
157 ranges[i] = new StealRange (fromInclusive, i, step);
159 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
161 int currentIndex = -1;
163 Action workerMethod = delegate {
164 int localWorker = Interlocked.Increment (ref currentIndex);
165 StealRange range = ranges[localWorker];
166 int index = range.V64.Actual;
167 int stopIndex = localWorker + 1 == num ? toExclusive : Math.Min (toExclusive, index + step);
168 TLocal local = localInit ();
170 ParallelLoopState state = new ParallelLoopState (infos);
171 CancellationToken token = parallelOptions.CancellationToken;
174 for (int i = index; i < stopIndex;) {
178 token.ThrowIfCancellationRequested ();
180 if (i >= stopIndex - range.V64.Stolen)
183 if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > i)
186 state.CurrentIteration = i;
187 local = body (i, state, local);
189 if (i + 1 >= stopIndex - range.V64.Stolen)
192 range.V64.Actual = ++i;
195 // Try toExclusive steal fromInclusive our right neighbor (cyclic)
196 int len = num + localWorker;
197 for (int sIndex = localWorker + 1; sIndex < len; ++sIndex) {
198 int extWorker = sIndex % num;
199 range = ranges[extWorker];
201 stopIndex = extWorker + 1 == num ? toExclusive : Math.Min (toExclusive, fromInclusive + (extWorker + 1) * step);
207 StealValue64 val = new StealValue64 ();
209 old = sixtyfour ? range.V64.Value : Interlocked.CompareExchange (ref range.V64.Value, 0, 0);
212 if (val.Actual >= stopIndex - val.Stolen - 2)
214 stolen = (val.Stolen += 1);
216 if (Interlocked.CompareExchange (ref range.V64.Value, val.Value, old) == old)
220 stolen = stopIndex - stolen;
222 if (stolen > range.V64.Actual)
223 local = body (stolen, state, local);
232 localFinally (local);
236 InitTasks (tasks, num, workerMethod, parallelOptions);
239 Task.WaitAll (tasks);
241 HandleExceptions (tasks, infos);
244 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
247 [StructLayout(LayoutKind.Explicit)]
248 struct StealValue64 {
259 public StealValue64 V64 = new StealValue64 ();
261 public StealRange (int fromInclusive, int i, int step)
263 V64.Actual = fromInclusive + i * step;
272 public static ParallelLoopResult For (long fromInclusive, long toExclusive, Action<long> body)
274 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
278 public static ParallelLoopResult For (long fromInclusive, long toExclusive, Action<long, ParallelLoopState> body)
280 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
284 public static ParallelLoopResult For (long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long> body)
286 return For (fromInclusive, toExclusive, parallelOptions, (index, state) => body (index));
290 public static ParallelLoopResult For (long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long, ParallelLoopState> body)
292 return For<object> (fromInclusive, toExclusive, parallelOptions, () => null, (i, s, l) => { body (i, s); return null; }, _ => {});
296 public static ParallelLoopResult For<TLocal> (long fromInclusive,
298 Func<TLocal> localInit,
299 Func<long, ParallelLoopState, TLocal, TLocal> body,
300 Action<TLocal> localFinally)
302 return For<TLocal> (fromInclusive, toExclusive, ParallelOptions.Default, localInit, body, localFinally);
305 [MonoTODO ("See how this can be refactored with the above For implementation")]
306 public static ParallelLoopResult For<TLocal> (long fromInclusive,
308 ParallelOptions parallelOptions,
309 Func<TLocal> localInit,
310 Func<long, ParallelLoopState, TLocal, TLocal> body,
311 Action<TLocal> localFinally)
314 throw new ArgumentNullException ("body");
315 if (localInit == null)
316 throw new ArgumentNullException ("localInit");
317 if (localFinally == null)
318 throw new ArgumentNullException ("localFinally");
319 if (parallelOptions == null)
320 throw new ArgumentNullException ("options");
321 if (fromInclusive >= toExclusive)
322 return new ParallelLoopResult (null, true);
324 throw new NotImplementedException ();
330 static ParallelLoopResult ForEach<TSource, TLocal> (Func<int, IList<IEnumerator<TSource>>> enumerable, ParallelOptions options,
331 Func<TLocal> init, Func<TSource, ParallelLoopState, TLocal, TLocal> action,
332 Action<TLocal> destruct)
334 if (enumerable == null)
335 throw new ArgumentNullException ("source");
337 throw new ArgumentNullException ("options");
339 throw new ArgumentNullException ("action");
341 throw new ArgumentNullException ("init");
342 if (destruct == null)
343 throw new ArgumentNullException ("destruct");
345 int num = Math.Min (GetBestWorkerNumber (),
346 options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
348 Task[] tasks = new Task[num];
349 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
351 SimpleConcurrentBag<TSource> bag = new SimpleConcurrentBag<TSource> (num);
352 const int bagCount = 5;
354 IList<IEnumerator<TSource>> slices = enumerable (num);
358 Action workerMethod = delegate {
359 IEnumerator<TSource> slice = slices[Interlocked.Increment (ref sliceIndex)];
361 TLocal local = init ();
362 ParallelLoopState state = new ParallelLoopState (infos);
363 int workIndex = bag.GetNextIndex ();
364 CancellationToken token = options.CancellationToken;
371 if (infos.IsStopped || infos.IsBroken.Value)
374 token.ThrowIfCancellationRequested ();
376 for (int i = 0; i < bagCount && (cont = slice.MoveNext ()); i++) {
377 bag.Add (workIndex, slice.Current);
380 for (int i = 0; i < bagCount && bag.TryTake (workIndex, out element); i++) {
384 token.ThrowIfCancellationRequested ();
386 local = action (element, state, local);
390 while (bag.TrySteal (workIndex, out element)) {
391 token.ThrowIfCancellationRequested ();
393 local = action (element, state, local);
395 if (infos.IsStopped || infos.IsBroken.Value)
403 InitTasks (tasks, num, workerMethod, options);
406 Task.WaitAll (tasks);
408 HandleExceptions (tasks, infos);
411 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
414 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, Action<TSource> body)
417 throw new ArgumentNullException ("source");
419 throw new ArgumentNullException ("body");
421 return ForEach<TSource, object> (Partitioner.Create (source),
422 ParallelOptions.Default,
424 (e, s, l) => { body (e); return null; },
428 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, Action<TSource, ParallelLoopState> body)
431 throw new ArgumentNullException ("source");
433 throw new ArgumentNullException ("body");
435 return ForEach<TSource, object> (Partitioner.Create (source),
436 ParallelOptions.Default,
438 (e, s, l) => { body (e, s); return null; },
442 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
443 Action<TSource, ParallelLoopState, long> body)
446 throw new ArgumentNullException ("source");
448 throw new ArgumentNullException ("body");
451 return ForEach<TSource, object> (Partitioner.Create (source),
452 ParallelOptions.Default,
454 (e, s, l) => { body (e, s, -1); return null; },
458 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
459 Action<TSource, ParallelLoopState> body)
462 throw new ArgumentNullException ("body");
464 return ForEach<TSource, object> (source,
465 ParallelOptions.Default,
467 (e, s, l) => { body (e, s); return null; },
471 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source,
472 Action<TSource, ParallelLoopState, long> body)
476 throw new ArgumentNullException ("body");
478 return ForEach<TSource, object> (source,
479 ParallelOptions.Default,
481 (e, s, i, l) => { body (e, s, i); return null; },
485 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
486 Action<TSource> body)
490 throw new ArgumentNullException ("body");
492 return ForEach<TSource, object> (source,
493 ParallelOptions.Default,
495 (e, s, l) => { body (e); return null; },
499 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
500 ParallelOptions parallelOptions,
501 Action<TSource> body)
504 throw new ArgumentNullException ("source");
506 throw new ArgumentNullException ("body");
508 return ForEach<TSource, object> (Partitioner.Create (source),
511 (e, s, l) => { body (e); return null; },
515 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
516 Action<TSource, ParallelLoopState> body)
519 throw new ArgumentNullException ("source");
521 throw new ArgumentNullException ("body");
523 return ForEach<TSource, object> (Partitioner.Create (source),
526 (e, s, l) => { body (e, s); return null; },
530 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
531 Action<TSource, ParallelLoopState, long> body)
534 throw new ArgumentNullException ("source");
536 throw new ArgumentNullException ("body");
538 return ForEach<TSource, object> (Partitioner.Create (source),
541 (e, s, i, l) => { body (e, s, i); return null; },
545 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
546 Action<TSource, ParallelLoopState, long> body)
550 throw new ArgumentNullException ("body");
552 return ForEach<TSource, object> (source,
555 (e, s, i, l) => { body (e, s, i); return null; },
559 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
560 Action<TSource> body)
563 throw new ArgumentNullException ("body");
565 return ForEach<TSource, object> (source,
568 (e, s, l) => { body (e); return null; },
572 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
573 Action<TSource, ParallelLoopState> body)
575 return ForEach<TSource, object> (source,
578 (e, s, l) => { body (e, s); return null; },
582 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
583 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
584 Action<TLocal> localFinally)
587 throw new ArgumentNullException ("source");
589 return ForEach<TSource, TLocal> ((Partitioner<TSource>)Partitioner.Create (source),
590 ParallelOptions.Default,
596 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
597 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
598 Action<TLocal> localFinally)
600 return ForEach<TSource, TLocal> (Partitioner.Create (source),
601 ParallelOptions.Default,
607 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, Func<TLocal> localInit,
608 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
609 Action<TLocal> localFinally)
611 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
614 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, Func<TLocal> localInit,
615 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
616 Action<TLocal> localFinally)
618 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
621 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
622 Func<TLocal> localInit,
623 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
624 Action<TLocal> localFinally)
627 throw new ArgumentNullException ("source");
629 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
632 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
633 Func<TLocal> localInit,
634 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
635 Action<TLocal> localFinally)
638 throw new ArgumentNullException ("source");
640 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
643 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, ParallelOptions parallelOptions,
644 Func<TLocal> localInit,
645 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
646 Action<TLocal> localFinally)
649 throw new ArgumentNullException ("source");
651 throw new ArgumentNullException ("body");
653 return ForEach<TSource, TLocal> (source.GetPartitions, parallelOptions, localInit, body, localFinally);
656 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
657 Func<TLocal> localInit,
658 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
659 Action<TLocal> localFinally)
662 throw new ArgumentNullException ("source");
664 throw new ArgumentNullException ("body");
666 return ForEach<KeyValuePair<long, TSource>, TLocal> (source.GetOrderablePartitions,
669 (e, s, l) => body (e.Value, s, e.Key, l),
675 public static void Invoke (params Action[] actions)
678 throw new ArgumentNullException ("actions");
680 Invoke (actions, (Action a) => Task.Factory.StartNew (a));
683 public static void Invoke (ParallelOptions parallelOptions, params Action[] actions)
685 if (parallelOptions == null)
686 throw new ArgumentNullException ("parallelOptions");
688 throw new ArgumentNullException ("actions");
690 Invoke (actions, (Action a) => Task.Factory.StartNew (a, parallelOptions.CancellationToken, TaskCreationOptions.None, parallelOptions.TaskScheduler));
693 static void Invoke (Action[] actions, Func<Action, Task> taskCreator)
695 if (actions.Length == 0)
696 throw new ArgumentException ("actions is empty");
698 // Execute it directly
699 if (actions.Length == 1 && actions[0] != null)
702 bool shouldThrow = false;
703 Task[] ts = Array.ConvertAll (actions, delegate (Action a) {
709 return taskCreator (a);
713 throw new ArgumentException ("One action in actions is null", "actions");
718 HandleExceptions (ts);
723 #region SpawnBestNumber, used by PLinq
724 internal static Task[] SpawnBestNumber (Action action, Action callback)
726 return SpawnBestNumber (action, -1, callback);
729 internal static Task[] SpawnBestNumber (Action action, int dop, Action callback)
731 return SpawnBestNumber (action, dop, false, callback);
734 internal static Task[] SpawnBestNumber (Action action, int dop, bool wait, Action callback)
736 // Get the optimum amount of worker to create
737 int num = dop == -1 ? (wait ? GetBestWorkerNumber () + 1 : GetBestWorkerNumber ()) : dop;
740 CountdownEvent evt = new CountdownEvent (num);
741 Task[] tasks = new Task [num];
742 for (int i = 0; i < num; i++) {
743 tasks [i] = Task.Factory.StartNew (() => {
746 if (callback != null && evt.IsSet)
751 // If explicitely told, wait for all workers to complete
752 // and thus let main thread participate in the processing
754 Task.WaitAll (tasks);