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;
31 namespace System.Threading.Tasks
33 public static class Parallel
35 internal static int GetBestWorkerNumber ()
37 return GetBestWorkerNumber (TaskScheduler.Current);
40 internal static int GetBestWorkerNumber (TaskScheduler scheduler)
42 return scheduler.MaximumConcurrencyLevel;
45 static int GetBestWorkerNumber (int from, int to, ParallelOptions options, out int step)
47 int num = Math.Min (GetBestWorkerNumber (),
48 options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
49 // Integer range that each task process
50 if ((step = (to - from) / num) < 5) {
52 num = (to - from) / 5;
60 static void HandleExceptions (IEnumerable<Task> tasks)
62 HandleExceptions (tasks, null);
65 static void HandleExceptions (IEnumerable<Task> tasks, ParallelLoopState.ExternalInfos infos)
67 List<Exception> exs = new List<Exception> ();
68 foreach (Task t in tasks) {
69 if (t.Exception != null)
70 exs.Add (t.Exception);
75 infos.IsExceptional = true;
77 throw new AggregateException (exs);
81 static void InitTasks (Task[] tasks, int count, Action action, ParallelOptions options)
83 TaskCreationOptions creation = TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent;
85 for (int i = 0; i < count; i++) {
87 tasks [i] = Task.Factory.StartNew (action, creation);
89 tasks [i] = Task.Factory.StartNew (action, options.CancellationToken, creation, options.TaskScheduler);
95 public static ParallelLoopResult For (int fromInclusive, int toExclusive, Action<int> body)
97 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
100 public static ParallelLoopResult For (int fromInclusive, int toExclusive, Action<int, ParallelLoopState> body)
102 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
105 public static ParallelLoopResult For (int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int> body)
107 return For (fromInclusive, toExclusive, parallelOptions, (index, state) => body (index));
110 public static ParallelLoopResult For (int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action<int, ParallelLoopState> body)
112 return For<object> (fromInclusive, toExclusive, parallelOptions, () => null, (i, s, l) => { body (i, s); return null; }, _ => {});
115 public static ParallelLoopResult For<TLocal> (int fromInclusive,
117 Func<TLocal> localInit,
118 Func<int, ParallelLoopState, TLocal, TLocal> body,
119 Action<TLocal> localFinally)
121 return For<TLocal> (fromInclusive, toExclusive, ParallelOptions.Default, localInit, body, localFinally);
124 public static ParallelLoopResult For<TLocal> (int fromInclusive,
126 ParallelOptions parallelOptions,
127 Func<TLocal> localInit,
128 Func<int, ParallelLoopState, TLocal, TLocal> body,
129 Action<TLocal> localFinally)
132 throw new ArgumentNullException ("body");
133 if (localInit == null)
134 throw new ArgumentNullException ("localInit");
135 if (localFinally == null)
136 throw new ArgumentNullException ("localFinally");
137 if (parallelOptions == null)
138 throw new ArgumentNullException ("options");
139 if (fromInclusive >= toExclusive)
140 return new ParallelLoopResult (null, true);
142 // Number of task toExclusive be launched (normally == Env.ProcessorCount)
144 int num = GetBestWorkerNumber (fromInclusive, toExclusive, parallelOptions, out step);
146 Task[] tasks = new Task [num];
148 StealRange[] ranges = new StealRange[num];
149 for (int i = 0; i < num; i++)
150 ranges[i] = new StealRange (fromInclusive, i, step);
152 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
154 int currentIndex = -1;
156 Action workerMethod = delegate {
157 int localWorker = Interlocked.Increment (ref currentIndex);
158 StealRange range = ranges[localWorker];
159 int index = range.Actual;
160 int stopIndex = localWorker + 1 == num ? toExclusive : Math.Min (toExclusive, index + step);
161 TLocal local = localInit ();
163 ParallelLoopState state = new ParallelLoopState (infos);
164 CancellationToken token = parallelOptions.CancellationToken;
167 for (int i = index; i < stopIndex; range.Actual = ++i) {
171 token.ThrowIfCancellationRequested ();
173 if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > i)
176 state.CurrentIteration = i;
177 local = body (i, state, local);
178 if (i >= stopIndex - range.Stolen)
182 // Try toExclusive steal fromInclusive our right neighbor (cyclic)
183 int len = num + localWorker;
184 for (int sIndex = localWorker + 1; sIndex < len; ++sIndex) {
185 int extWorker = sIndex % num;
186 range = ranges[extWorker];
188 stopIndex = extWorker + 1 == num ? toExclusive : Math.Min (toExclusive, fromInclusive + (extWorker + 1) * step);
192 stolen = range.Stolen;
193 if (stopIndex - stolen > range.Actual)
195 } while (Interlocked.CompareExchange (ref range.Stolen, stolen + 1, stolen) != stolen);
197 stolen = stopIndex - stolen - 1;
199 if (stolen > range.Actual)
200 local = body (stolen, state, local);
206 localFinally (local);
210 InitTasks (tasks, num, workerMethod, parallelOptions);
213 Task.WaitAll (tasks);
215 HandleExceptions (tasks, infos);
218 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
226 public StealRange (int fromInclusive, int i, int step)
228 Actual = fromInclusive + i * step;
237 public static ParallelLoopResult For (long fromInclusive, long toExclusive, Action<long> body)
239 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
243 public static ParallelLoopResult For (long fromInclusive, long toExclusive, Action<long, ParallelLoopState> body)
245 return For (fromInclusive, toExclusive, ParallelOptions.Default, body);
249 public static ParallelLoopResult For (long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long> body)
251 return For (fromInclusive, toExclusive, parallelOptions, (index, state) => body (index));
255 public static ParallelLoopResult For (long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action<long, ParallelLoopState> body)
257 return For<object> (fromInclusive, toExclusive, parallelOptions, () => null, (i, s, l) => { body (i, s); return null; }, _ => {});
261 public static ParallelLoopResult For<TLocal> (long fromInclusive,
263 Func<TLocal> localInit,
264 Func<long, ParallelLoopState, TLocal, TLocal> body,
265 Action<TLocal> localFinally)
267 return For<TLocal> (fromInclusive, toExclusive, ParallelOptions.Default, localInit, body, localFinally);
270 [MonoTODO ("See how this can be refactored with the above For implementation")]
271 public static ParallelLoopResult For<TLocal> (long fromInclusive,
273 ParallelOptions parallelOptions,
274 Func<TLocal> localInit,
275 Func<long, ParallelLoopState, TLocal, TLocal> body,
276 Action<TLocal> localFinally)
279 throw new ArgumentNullException ("body");
280 if (localInit == null)
281 throw new ArgumentNullException ("localInit");
282 if (localFinally == null)
283 throw new ArgumentNullException ("localFinally");
284 if (parallelOptions == null)
285 throw new ArgumentNullException ("options");
286 if (fromInclusive >= toExclusive)
287 return new ParallelLoopResult (null, true);
289 throw new NotImplementedException ();
295 static ParallelLoopResult ForEach<TSource, TLocal> (Func<int, IList<IEnumerator<TSource>>> enumerable, ParallelOptions options,
296 Func<TLocal> init, Func<TSource, ParallelLoopState, TLocal, TLocal> action,
297 Action<TLocal> destruct)
299 if (enumerable == null)
300 throw new ArgumentNullException ("source");
302 throw new ArgumentNullException ("options");
304 throw new ArgumentNullException ("action");
306 throw new ArgumentNullException ("init");
307 if (destruct == null)
308 throw new ArgumentNullException ("destruct");
310 int num = Math.Min (GetBestWorkerNumber (),
311 options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
313 Task[] tasks = new Task[num];
314 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
316 SimpleConcurrentBag<TSource> bag = new SimpleConcurrentBag<TSource> (num);
317 const int bagCount = 5;
319 IList<IEnumerator<TSource>> slices = enumerable (num);
323 Action workerMethod = delegate {
324 IEnumerator<TSource> slice = slices[Interlocked.Increment (ref sliceIndex)];
326 TLocal local = init ();
327 ParallelLoopState state = new ParallelLoopState (infos);
328 int workIndex = bag.GetNextIndex ();
329 CancellationToken token = options.CancellationToken;
336 if (infos.IsStopped || infos.IsBroken.Value)
339 token.ThrowIfCancellationRequested ();
341 for (int i = 0; i < bagCount && (cont = slice.MoveNext ()); i++) {
342 bag.Add (workIndex, slice.Current);
345 for (int i = 0; i < bagCount && bag.TryTake (workIndex, out element); i++) {
349 token.ThrowIfCancellationRequested ();
351 local = action (element, state, local);
355 while (bag.TrySteal (workIndex, out element)) {
356 token.ThrowIfCancellationRequested ();
358 local = action (element, state, local);
360 if (infos.IsStopped || infos.IsBroken.Value)
368 InitTasks (tasks, num, workerMethod, options);
371 Task.WaitAll (tasks);
373 HandleExceptions (tasks, infos);
376 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
379 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, Action<TSource> body)
382 throw new ArgumentNullException ("source");
384 throw new ArgumentNullException ("body");
386 return ForEach<TSource, object> (Partitioner.Create (source),
387 ParallelOptions.Default,
389 (e, s, l) => { body (e); return null; },
393 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, Action<TSource, ParallelLoopState> body)
396 throw new ArgumentNullException ("source");
398 throw new ArgumentNullException ("body");
400 return ForEach<TSource, object> (Partitioner.Create (source),
401 ParallelOptions.Default,
403 (e, s, l) => { body (e, s); return null; },
407 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
408 Action<TSource, ParallelLoopState, long> body)
411 throw new ArgumentNullException ("source");
413 throw new ArgumentNullException ("body");
416 return ForEach<TSource, object> (Partitioner.Create (source),
417 ParallelOptions.Default,
419 (e, s, l) => { body (e, s, -1); return null; },
423 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
424 Action<TSource, ParallelLoopState> body)
427 throw new ArgumentNullException ("body");
429 return ForEach<TSource, object> (source,
430 ParallelOptions.Default,
432 (e, s, l) => { body (e, s); return null; },
436 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source,
437 Action<TSource, ParallelLoopState, long> body)
441 throw new ArgumentNullException ("body");
443 return ForEach<TSource, object> (source,
444 ParallelOptions.Default,
446 (e, s, i, l) => { body (e, s, i); return null; },
450 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
451 Action<TSource> body)
455 throw new ArgumentNullException ("body");
457 return ForEach<TSource, object> (source,
458 ParallelOptions.Default,
460 (e, s, l) => { body (e); return null; },
464 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
465 ParallelOptions parallelOptions,
466 Action<TSource> body)
469 throw new ArgumentNullException ("source");
471 throw new ArgumentNullException ("body");
473 return ForEach<TSource, object> (Partitioner.Create (source),
476 (e, s, l) => { body (e); return null; },
480 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
481 Action<TSource, ParallelLoopState> body)
484 throw new ArgumentNullException ("source");
486 throw new ArgumentNullException ("body");
488 return ForEach<TSource, object> (Partitioner.Create (source),
491 (e, s, l) => { body (e, s); return null; },
495 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
496 Action<TSource, ParallelLoopState, long> body)
499 throw new ArgumentNullException ("source");
501 throw new ArgumentNullException ("body");
503 return ForEach<TSource, object> (Partitioner.Create (source),
506 (e, s, i, l) => { body (e, s, i); return null; },
510 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
511 Action<TSource, ParallelLoopState, long> body)
515 throw new ArgumentNullException ("body");
517 return ForEach<TSource, object> (source,
520 (e, s, i, l) => { body (e, s, i); return null; },
524 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
525 Action<TSource> body)
528 throw new ArgumentNullException ("body");
530 return ForEach<TSource, object> (source,
533 (e, s, l) => { body (e); return null; },
537 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
538 Action<TSource, ParallelLoopState> body)
540 return ForEach<TSource, object> (source,
543 (e, s, l) => { body (e, s); return null; },
547 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
548 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
549 Action<TLocal> localFinally)
552 throw new ArgumentNullException ("source");
554 return ForEach<TSource, TLocal> ((Partitioner<TSource>)Partitioner.Create (source),
555 ParallelOptions.Default,
561 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
562 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
563 Action<TLocal> localFinally)
565 return ForEach<TSource, TLocal> (Partitioner.Create (source),
566 ParallelOptions.Default,
572 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, Func<TLocal> localInit,
573 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
574 Action<TLocal> localFinally)
576 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
579 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, Func<TLocal> localInit,
580 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
581 Action<TLocal> localFinally)
583 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
586 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
587 Func<TLocal> localInit,
588 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
589 Action<TLocal> localFinally)
592 throw new ArgumentNullException ("source");
594 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
597 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
598 Func<TLocal> localInit,
599 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
600 Action<TLocal> localFinally)
603 throw new ArgumentNullException ("source");
605 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
608 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, ParallelOptions parallelOptions,
609 Func<TLocal> localInit,
610 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
611 Action<TLocal> localFinally)
614 throw new ArgumentNullException ("source");
616 throw new ArgumentNullException ("body");
618 return ForEach<TSource, TLocal> (source.GetPartitions, parallelOptions, localInit, body, localFinally);
621 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
622 Func<TLocal> localInit,
623 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
624 Action<TLocal> localFinally)
627 throw new ArgumentNullException ("source");
629 throw new ArgumentNullException ("body");
631 return ForEach<KeyValuePair<long, TSource>, TLocal> (source.GetOrderablePartitions,
634 (e, s, l) => body (e.Value, s, e.Key, l),
640 public static void Invoke (params Action[] actions)
643 throw new ArgumentNullException ("actions");
645 Invoke (actions, (Action a) => Task.Factory.StartNew (a));
648 public static void Invoke (ParallelOptions parallelOptions, params Action[] actions)
650 if (parallelOptions == null)
651 throw new ArgumentNullException ("parallelOptions");
653 throw new ArgumentNullException ("actions");
655 Invoke (actions, (Action a) => Task.Factory.StartNew (a, parallelOptions.CancellationToken, TaskCreationOptions.None, parallelOptions.TaskScheduler));
658 static void Invoke (Action[] actions, Func<Action, Task> taskCreator)
660 if (actions.Length == 0)
661 throw new ArgumentException ("actions is empty");
663 // Execute it directly
664 if (actions.Length == 1 && actions[0] != null)
667 bool shouldThrow = false;
668 Task[] ts = Array.ConvertAll (actions, delegate (Action a) {
674 return taskCreator (a);
678 throw new ArgumentException ("One action in actions is null", "actions");
683 HandleExceptions (ts);
688 #region SpawnBestNumber, used by PLinq
689 internal static Task[] SpawnBestNumber (Action action, Action callback)
691 return SpawnBestNumber (action, -1, callback);
694 internal static Task[] SpawnBestNumber (Action action, int dop, Action callback)
696 return SpawnBestNumber (action, dop, false, callback);
699 internal static Task[] SpawnBestNumber (Action action, int dop, bool wait, Action callback)
701 // Get the optimum amount of worker to create
702 int num = dop == -1 ? (wait ? GetBestWorkerNumber () + 1 : GetBestWorkerNumber ()) : dop;
705 CountdownEvent evt = new CountdownEvent (num);
706 Task[] tasks = new Task [num];
707 for (int i = 0; i < num; i++) {
708 tasks [i] = Task.Factory.StartNew (() => {
711 if (callback != null && evt.IsSet)
716 // If explicitely told, wait for all workers to complete
717 // and thus let main thread participate in the processing
719 Task.WaitAll (tasks);