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 Math.Min (Environment.ProcessorCount, (scheduler ?? TaskScheduler.Current).MaximumConcurrencyLevel);
52 static int GetBestWorkerNumber (int from, int to, ParallelOptions options, out int step)
54 int num = GetBestWorkerNumber(options.TaskScheduler);
55 if (options != null && options.MaxDegreeOfParallelism != -1)
56 num = Math.Min (options.MaxDegreeOfParallelism, num);
57 // Integer range that each task process
58 if ((step = (to - from) / num) < 5) {
60 num = (to - from) / 5;
68 static void HandleExceptions (IEnumerable<Task> tasks)
70 HandleExceptions (tasks, null);
73 static void HandleExceptions (IEnumerable<Task> tasks, ParallelLoopState.ExternalInfos infos)
75 List<Exception> exs = new List<Exception> ();
76 foreach (Task t in tasks) {
77 if (t.Exception != null)
78 exs.Add (t.Exception);
83 infos.IsExceptional = true;
85 throw new AggregateException (exs).Flatten ();
89 static void InitTasks (Task[] tasks, int count, Action action, ParallelOptions options)
91 TaskCreationOptions creation = TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
93 for (int i = 0; i < count; i++) {
95 tasks [i] = Task.Factory.StartNew (action, creation);
97 tasks [i] = Task.Factory.StartNew (action, options.CancellationToken, creation, options.TaskScheduler);
103 public static ParallelLoopResult For (int fromInclusive, int toExclusive, Action<int> body)
105 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
108 public static ParallelLoopResult For (int fromInclusive, int toExclusive, Action<int, ParallelLoopState> body)
110 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
113 public static ParallelLoopResult For (int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int> body)
115 return For (fromInclusive, toExclusive, parallelOptions, (index, state) => body (index));
118 public static ParallelLoopResult For (int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int, ParallelLoopState> body)
120 return For<object> (fromInclusive, toExclusive, parallelOptions, () => null, (i, s, l) => { body (i, s); return null; }, _ => {});
123 public static ParallelLoopResult For<TLocal> (int fromInclusive,
125 Func<TLocal> localInit,
126 Func<int, ParallelLoopState, TLocal, TLocal> body,
127 Action<TLocal> localFinally)
129 return For<TLocal> (fromInclusive, toExclusive, ParallelOptions.Default, localInit, body, localFinally);
132 public static ParallelLoopResult For<TLocal> (int fromInclusive,
134 ParallelOptions parallelOptions,
135 Func<TLocal> localInit,
136 Func<int, ParallelLoopState, TLocal, TLocal> body,
137 Action<TLocal> localFinally)
140 throw new ArgumentNullException ("body");
141 if (localInit == null)
142 throw new ArgumentNullException ("localInit");
143 if (localFinally == null)
144 throw new ArgumentNullException ("localFinally");
145 if (parallelOptions == null)
146 throw new ArgumentNullException ("options");
147 if (fromInclusive >= toExclusive)
148 return new ParallelLoopResult (null, true);
150 // Number of task toExclusive be launched (normally == Env.ProcessorCount)
152 int num = GetBestWorkerNumber (fromInclusive, toExclusive, parallelOptions, out step);
154 Task[] tasks = new Task [num];
156 StealRange[] ranges = new StealRange[num];
157 for (int i = 0; i < num; i++)
158 ranges[i] = new StealRange (fromInclusive, i, step);
160 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
162 int currentIndex = -1;
164 Action workerMethod = delegate {
165 int localWorker = Interlocked.Increment (ref currentIndex);
166 StealRange range = ranges[localWorker];
167 int index = range.V64.Actual;
168 int stopIndex = localWorker + 1 == num ? toExclusive : Math.Min (toExclusive, index + step);
169 TLocal local = localInit ();
171 ParallelLoopState state = new ParallelLoopState (infos);
172 CancellationToken token = parallelOptions.CancellationToken;
175 for (int i = index; i < stopIndex;) {
179 token.ThrowIfCancellationRequested ();
181 if (i >= stopIndex - range.V64.Stolen)
184 if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > i)
187 state.CurrentIteration = i;
188 local = body (i, state, local);
190 if (i + 1 >= stopIndex - range.V64.Stolen)
193 range.V64.Actual = ++i;
196 // Try toExclusive steal fromInclusive our right neighbor (cyclic)
197 int len = num + localWorker;
198 for (int sIndex = localWorker + 1; sIndex < len; ++sIndex) {
199 int extWorker = sIndex % num;
200 range = ranges[extWorker];
202 stopIndex = extWorker + 1 == num ? toExclusive : Math.Min (toExclusive, fromInclusive + (extWorker + 1) * step);
208 StealValue64 val = new StealValue64 ();
210 old = sixtyfour ? range.V64.Value : Interlocked.CompareExchange (ref range.V64.Value, 0, 0);
213 if (val.Actual >= stopIndex - val.Stolen - 2)
215 stolen = (val.Stolen += 1);
217 if (Interlocked.CompareExchange (ref range.V64.Value, val.Value, old) == old)
221 stolen = stopIndex - stolen;
223 if (stolen > range.V64.Actual)
224 local = body (stolen, state, local);
233 localFinally (local);
237 InitTasks (tasks, num, workerMethod, parallelOptions);
240 Task.WaitAll (tasks);
242 HandleExceptions (tasks, infos);
245 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
248 [StructLayout(LayoutKind.Explicit)]
249 struct StealValue64 {
260 public StealValue64 V64 = new StealValue64 ();
262 public StealRange (int fromInclusive, int i, int step)
264 V64.Actual = fromInclusive + i * step;
273 public static ParallelLoopResult For (long fromInclusive, long toExclusive, Action<long> body)
275 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
279 public static ParallelLoopResult For (long fromInclusive, long toExclusive, Action<long, ParallelLoopState> body)
281 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
285 public static ParallelLoopResult For (long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long> body)
287 return For (fromInclusive, toExclusive, parallelOptions, (index, state) => body (index));
291 public static ParallelLoopResult For (long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long, ParallelLoopState> body)
293 return For<object> (fromInclusive, toExclusive, parallelOptions, () => null, (i, s, l) => { body (i, s); return null; }, _ => {});
297 public static ParallelLoopResult For<TLocal> (long fromInclusive,
299 Func<TLocal> localInit,
300 Func<long, ParallelLoopState, TLocal, TLocal> body,
301 Action<TLocal> localFinally)
303 return For<TLocal> (fromInclusive, toExclusive, ParallelOptions.Default, localInit, body, localFinally);
306 [MonoTODO ("See how this can be refactored with the above For implementation")]
307 public static ParallelLoopResult For<TLocal> (long fromInclusive,
309 ParallelOptions parallelOptions,
310 Func<TLocal> localInit,
311 Func<long, ParallelLoopState, TLocal, TLocal> body,
312 Action<TLocal> localFinally)
315 throw new ArgumentNullException ("body");
316 if (localInit == null)
317 throw new ArgumentNullException ("localInit");
318 if (localFinally == null)
319 throw new ArgumentNullException ("localFinally");
320 if (parallelOptions == null)
321 throw new ArgumentNullException ("options");
322 if (fromInclusive >= toExclusive)
323 return new ParallelLoopResult (null, true);
325 throw new NotImplementedException ();
331 static ParallelLoopResult ForEach<TSource, TLocal> (Func<int, IList<IEnumerator<TSource>>> enumerable, ParallelOptions options,
332 Func<TLocal> init, Func<TSource, ParallelLoopState, TLocal, TLocal> action,
333 Action<TLocal> destruct)
335 if (enumerable == null)
336 throw new ArgumentNullException ("source");
338 throw new ArgumentNullException ("options");
340 throw new ArgumentNullException ("action");
342 throw new ArgumentNullException ("init");
343 if (destruct == null)
344 throw new ArgumentNullException ("destruct");
346 int num = Math.Min (GetBestWorkerNumber (options.TaskScheduler),
347 options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
349 Task[] tasks = new Task[num];
350 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
352 SimpleConcurrentBag<TSource> bag = new SimpleConcurrentBag<TSource> (num);
353 const int bagCount = 5;
355 IList<IEnumerator<TSource>> slices = enumerable (num);
359 Action workerMethod = delegate {
360 IEnumerator<TSource> slice = slices[Interlocked.Increment (ref sliceIndex)];
362 TLocal local = init ();
363 ParallelLoopState state = new ParallelLoopState (infos);
364 int workIndex = bag.GetNextIndex ();
365 CancellationToken token = options.CancellationToken;
372 if (infos.IsStopped || infos.IsBroken.Value)
375 token.ThrowIfCancellationRequested ();
377 for (int i = 0; i < bagCount && (cont = slice.MoveNext ()); i++) {
378 bag.Add (workIndex, slice.Current);
381 for (int i = 0; i < bagCount && bag.TryTake (workIndex, out element); i++) {
385 token.ThrowIfCancellationRequested ();
387 local = action (element, state, local);
391 while (bag.TrySteal (workIndex, out element)) {
392 token.ThrowIfCancellationRequested ();
394 local = action (element, state, local);
396 if (infos.IsStopped || infos.IsBroken.Value)
404 InitTasks (tasks, num, workerMethod, options);
407 Task.WaitAll (tasks);
409 HandleExceptions (tasks, infos);
412 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
415 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, Action<TSource> body)
418 throw new ArgumentNullException ("source");
420 throw new ArgumentNullException ("body");
422 return ForEach<TSource, object> (Partitioner.Create (source),
423 ParallelOptions.Default,
425 (e, s, l) => { body (e); return null; },
429 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, Action<TSource, ParallelLoopState> body)
432 throw new ArgumentNullException ("source");
434 throw new ArgumentNullException ("body");
436 return ForEach<TSource, object> (Partitioner.Create (source),
437 ParallelOptions.Default,
439 (e, s, l) => { body (e, s); return null; },
443 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
444 Action<TSource, ParallelLoopState, long> body)
447 throw new ArgumentNullException ("source");
449 throw new ArgumentNullException ("body");
452 return ForEach<TSource, object> (Partitioner.Create (source),
453 ParallelOptions.Default,
455 (e, s, l) => { body (e, s, -1); return null; },
459 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
460 Action<TSource, ParallelLoopState> body)
463 throw new ArgumentNullException ("body");
465 return ForEach<TSource, object> (source,
466 ParallelOptions.Default,
468 (e, s, l) => { body (e, s); return null; },
472 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source,
473 Action<TSource, ParallelLoopState, long> body)
477 throw new ArgumentNullException ("body");
479 return ForEach<TSource, object> (source,
480 ParallelOptions.Default,
482 (e, s, i, l) => { body (e, s, i); return null; },
486 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
487 Action<TSource> body)
491 throw new ArgumentNullException ("body");
493 return ForEach<TSource, object> (source,
494 ParallelOptions.Default,
496 (e, s, l) => { body (e); return null; },
500 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
501 ParallelOptions parallelOptions,
502 Action<TSource> body)
505 throw new ArgumentNullException ("source");
507 throw new ArgumentNullException ("body");
509 return ForEach<TSource, object> (Partitioner.Create (source),
512 (e, s, l) => { body (e); return null; },
516 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
517 Action<TSource, ParallelLoopState> body)
520 throw new ArgumentNullException ("source");
522 throw new ArgumentNullException ("body");
524 return ForEach<TSource, object> (Partitioner.Create (source),
527 (e, s, l) => { body (e, s); return null; },
531 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
532 Action<TSource, ParallelLoopState, long> body)
535 throw new ArgumentNullException ("source");
537 throw new ArgumentNullException ("body");
539 return ForEach<TSource, object> (Partitioner.Create (source),
542 (e, s, i, l) => { body (e, s, i); return null; },
546 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
547 Action<TSource, ParallelLoopState, long> body)
551 throw new ArgumentNullException ("body");
553 return ForEach<TSource, object> (source,
556 (e, s, i, l) => { body (e, s, i); return null; },
560 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
561 Action<TSource> body)
564 throw new ArgumentNullException ("body");
566 return ForEach<TSource, object> (source,
569 (e, s, l) => { body (e); return null; },
573 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
574 Action<TSource, ParallelLoopState> body)
576 return ForEach<TSource, object> (source,
579 (e, s, l) => { body (e, s); return null; },
583 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
584 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
585 Action<TLocal> localFinally)
588 throw new ArgumentNullException ("source");
590 return ForEach<TSource, TLocal> ((Partitioner<TSource>)Partitioner.Create (source),
591 ParallelOptions.Default,
597 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
598 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
599 Action<TLocal> localFinally)
601 return ForEach<TSource, TLocal> (Partitioner.Create (source),
602 ParallelOptions.Default,
608 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, Func<TLocal> localInit,
609 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
610 Action<TLocal> localFinally)
612 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
615 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, Func<TLocal> localInit,
616 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
617 Action<TLocal> localFinally)
619 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
622 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
623 Func<TLocal> localInit,
624 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
625 Action<TLocal> localFinally)
628 throw new ArgumentNullException ("source");
630 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
633 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
634 Func<TLocal> localInit,
635 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
636 Action<TLocal> localFinally)
639 throw new ArgumentNullException ("source");
641 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
644 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, ParallelOptions parallelOptions,
645 Func<TLocal> localInit,
646 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
647 Action<TLocal> localFinally)
650 throw new ArgumentNullException ("source");
652 throw new ArgumentNullException ("body");
654 return ForEach<TSource, TLocal> (source.GetPartitions, parallelOptions, localInit, body, localFinally);
657 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
658 Func<TLocal> localInit,
659 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
660 Action<TLocal> localFinally)
663 throw new ArgumentNullException ("source");
665 throw new ArgumentNullException ("body");
667 return ForEach<KeyValuePair<long, TSource>, TLocal> (source.GetOrderablePartitions,
670 (e, s, l) => body (e.Value, s, e.Key, l),
676 public static void Invoke (params Action[] actions)
679 throw new ArgumentNullException ("actions");
681 Invoke (ParallelOptions.Default, actions);
684 public static void Invoke (ParallelOptions parallelOptions, params Action[] actions)
686 if (parallelOptions == null)
687 throw new ArgumentNullException ("parallelOptions");
689 throw new ArgumentNullException ("actions");
690 if (actions.Length == 0)
691 throw new ArgumentException ("actions is empty");
692 foreach (var a in actions)
694 throw new ArgumentException ("One action in actions is null", "actions");
695 if (actions.Length == 1) {
700 Task[] ts = new Task[actions.Length];
701 for (int i = 0; i < ts.Length; i++)
702 ts[i] = Task.Factory.StartNew (actions[i],
703 parallelOptions.CancellationToken,
704 TaskCreationOptions.None,
705 parallelOptions.TaskScheduler);
708 Task.WaitAll (ts, parallelOptions.CancellationToken);
710 HandleExceptions (ts);
715 #region SpawnBestNumber, used by PLinq
716 internal static Task[] SpawnBestNumber (Action action, Action callback)
718 return SpawnBestNumber (action, -1, callback);
721 internal static Task[] SpawnBestNumber (Action action, int dop, Action callback)
723 return SpawnBestNumber (action, dop, false, callback);
726 internal static Task[] SpawnBestNumber (Action action, int dop, bool wait, Action callback)
728 // Get the optimum amount of worker to create
729 int num = dop == -1 ? (wait ? GetBestWorkerNumber () + 1 : GetBestWorkerNumber ()) : dop;
732 CountdownEvent evt = new CountdownEvent (num);
733 Task[] tasks = new Task [num];
734 for (int i = 0; i < num; i++) {
735 tasks [i] = Task.Factory.StartNew (() => {
738 if (callback != null && evt.IsSet)
743 // If explicitely told, wait for all workers to complete
744 // and thus let main thread participate in the processing
746 Task.WaitAll (tasks);