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;
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;
235 static ParallelLoopResult ForEach<TSource, TLocal> (Func<int, IList<IEnumerator<TSource>>> enumerable, ParallelOptions options,
236 Func<TLocal> init, Func<TSource, ParallelLoopState, TLocal, TLocal> action,
237 Action<TLocal> destruct)
239 if (enumerable == null)
240 throw new ArgumentNullException ("source");
242 throw new ArgumentNullException ("options");
244 throw new ArgumentNullException ("action");
246 throw new ArgumentNullException ("init");
247 if (destruct == null)
248 throw new ArgumentNullException ("destruct");
250 int num = Math.Min (GetBestWorkerNumber (),
251 options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
253 Task[] tasks = new Task[num];
254 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
256 SimpleConcurrentBag<TSource> bag = new SimpleConcurrentBag<TSource> (num);
257 const int bagCount = 5;
259 IList<IEnumerator<TSource>> slices = enumerable (num);
263 Action workerMethod = delegate {
264 IEnumerator<TSource> slice = slices[Interlocked.Increment (ref sliceIndex)];
266 TLocal local = init ();
267 ParallelLoopState state = new ParallelLoopState (infos);
268 int workIndex = bag.GetNextIndex ();
269 CancellationToken token = options.CancellationToken;
276 if (infos.IsStopped || infos.IsBroken.Value)
279 token.ThrowIfCancellationRequested ();
281 for (int i = 0; i < bagCount && (cont = slice.MoveNext ()); i++) {
282 bag.Add (workIndex, slice.Current);
285 for (int i = 0; i < bagCount && bag.TryTake (workIndex, out element); i++) {
289 token.ThrowIfCancellationRequested ();
291 local = action (element, state, local);
295 while (bag.TrySteal (workIndex, out element)) {
296 token.ThrowIfCancellationRequested ();
298 local = action (element, state, local);
300 if (infos.IsStopped || infos.IsBroken.Value)
308 InitTasks (tasks, num, workerMethod, options);
311 Task.WaitAll (tasks);
313 HandleExceptions (tasks, infos);
316 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
319 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, Action<TSource> body)
322 throw new ArgumentNullException ("source");
324 throw new ArgumentNullException ("body");
326 return ForEach<TSource, object> (Partitioner.Create (source),
327 ParallelOptions.Default,
329 (e, s, l) => { body (e); return null; },
333 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, Action<TSource, ParallelLoopState> body)
336 throw new ArgumentNullException ("source");
338 throw new ArgumentNullException ("body");
340 return ForEach<TSource, object> (Partitioner.Create (source),
341 ParallelOptions.Default,
343 (e, s, l) => { body (e, s); return null; },
347 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
348 Action<TSource, ParallelLoopState, long> body)
351 throw new ArgumentNullException ("source");
353 throw new ArgumentNullException ("body");
356 return ForEach<TSource, object> (Partitioner.Create (source),
357 ParallelOptions.Default,
359 (e, s, l) => { body (e, s, -1); return null; },
363 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
364 Action<TSource, ParallelLoopState> body)
367 throw new ArgumentNullException ("body");
369 return ForEach<TSource, object> (source,
370 ParallelOptions.Default,
372 (e, s, l) => { body (e, s); return null; },
376 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source,
377 Action<TSource, ParallelLoopState, long> body)
381 throw new ArgumentNullException ("body");
383 return ForEach<TSource, object> (source,
384 ParallelOptions.Default,
386 (e, s, i, l) => { body (e, s, i); return null; },
390 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
391 Action<TSource> body)
395 throw new ArgumentNullException ("body");
397 return ForEach<TSource, object> (source,
398 ParallelOptions.Default,
400 (e, s, l) => { body (e); return null; },
404 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source,
405 ParallelOptions parallelOptions,
406 Action<TSource> body)
409 throw new ArgumentNullException ("source");
411 throw new ArgumentNullException ("body");
413 return ForEach<TSource, object> (Partitioner.Create (source),
416 (e, s, l) => { body (e); return null; },
420 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
421 Action<TSource, ParallelLoopState> body)
424 throw new ArgumentNullException ("source");
426 throw new ArgumentNullException ("body");
428 return ForEach<TSource, object> (Partitioner.Create (source),
431 (e, s, l) => { body (e, s); return null; },
435 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
436 Action<TSource, ParallelLoopState, long> body)
439 throw new ArgumentNullException ("source");
441 throw new ArgumentNullException ("body");
443 return ForEach<TSource, object> (Partitioner.Create (source),
446 (e, s, i, l) => { body (e, s, i); return null; },
450 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
451 Action<TSource, ParallelLoopState, long> body)
455 throw new ArgumentNullException ("body");
457 return ForEach<TSource, object> (source,
460 (e, s, i, l) => { body (e, s, i); return null; },
464 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
465 Action<TSource> body)
468 throw new ArgumentNullException ("body");
470 return ForEach<TSource, object> (source,
473 (e, s, l) => { body (e); return null; },
477 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
478 Action<TSource, ParallelLoopState> body)
480 return ForEach<TSource, object> (source,
483 (e, s, l) => { body (e, s); return null; },
487 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
488 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
489 Action<TLocal> localFinally)
492 throw new ArgumentNullException ("source");
494 return ForEach<TSource, TLocal> ((Partitioner<TSource>)Partitioner.Create (source),
495 ParallelOptions.Default,
501 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
502 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
503 Action<TLocal> localFinally)
505 return ForEach<TSource, TLocal> (Partitioner.Create (source),
506 ParallelOptions.Default,
512 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, Func<TLocal> localInit,
513 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
514 Action<TLocal> localFinally)
516 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
519 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, Func<TLocal> localInit,
520 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
521 Action<TLocal> localFinally)
523 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
526 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
527 Func<TLocal> localInit,
528 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
529 Action<TLocal> localFinally)
532 throw new ArgumentNullException ("source");
534 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
537 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
538 Func<TLocal> localInit,
539 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
540 Action<TLocal> localFinally)
543 throw new ArgumentNullException ("source");
545 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
548 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, ParallelOptions parallelOptions,
549 Func<TLocal> localInit,
550 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
551 Action<TLocal> localFinally)
554 throw new ArgumentNullException ("source");
556 throw new ArgumentNullException ("body");
558 return ForEach<TSource, TLocal> (source.GetPartitions, parallelOptions, localInit, body, localFinally);
561 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
562 Func<TLocal> localInit,
563 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
564 Action<TLocal> localFinally)
567 throw new ArgumentNullException ("source");
569 throw new ArgumentNullException ("body");
571 return ForEach<KeyValuePair<long, TSource>, TLocal> (source.GetOrderablePartitions,
574 (e, s, l) => body (e.Value, s, e.Key, l),
580 public static void Invoke (params Action[] actions)
583 throw new ArgumentNullException ("actions");
585 Invoke (actions, (Action a) => Task.Factory.StartNew (a));
588 public static void Invoke (ParallelOptions parallelOptions, params Action[] actions)
590 if (parallelOptions == null)
591 throw new ArgumentNullException ("parallelOptions");
593 throw new ArgumentNullException ("actions");
595 Invoke (actions, (Action a) => Task.Factory.StartNew (a, parallelOptions.CancellationToken, TaskCreationOptions.None, parallelOptions.TaskScheduler));
598 static void Invoke (Action[] actions, Func<Action, Task> taskCreator)
600 if (actions.Length == 0)
601 throw new ArgumentException ("actions is empty");
603 // Execute it directly
604 if (actions.Length == 1 && actions[0] != null)
607 bool shouldThrow = false;
608 Task[] ts = Array.ConvertAll (actions, delegate (Action a) {
614 return taskCreator (a);
618 throw new ArgumentException ("One action in actions is null", "actions");
623 HandleExceptions (ts);
628 #region SpawnBestNumber, used by PLinq
629 internal static Task[] SpawnBestNumber (Action action, Action callback)
631 return SpawnBestNumber (action, -1, callback);
634 internal static Task[] SpawnBestNumber (Action action, int dop, Action callback)
636 return SpawnBestNumber (action, dop, false, callback);
639 internal static Task[] SpawnBestNumber (Action action, int dop, bool wait, Action callback)
641 // Get the optimum amount of worker to create
642 int num = dop == -1 ? (wait ? GetBestWorkerNumber () + 1 : GetBestWorkerNumber ()) : dop;
645 CountdownEvent evt = new CountdownEvent (num);
646 Task[] tasks = new Task [num];
647 for (int i = 0; i < num; i++) {
648 tasks [i] = Task.Factory.StartNew (() => {
651 if (callback != null && evt.IsSet)
656 // If explicitely told, wait for all workers to complete
657 // and thus let main thread participate in the processing
659 Task.WaitAll (tasks);