4 // Copyright (c) 2008 Jérémie "Garuma" Laval
6 // Permission is hereby granted, free of charge, to any person obtaining a copy
7 // of this software and associated documentation files (the "Software"), to deal
8 // in the Software without restriction, including without limitation the rights
9 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 // copies of the Software, and to permit persons to whom the Software is
11 // furnished to do so, subject to the following conditions:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 // 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 void HandleExceptions (IEnumerable<Task> tasks)
47 HandleExceptions (tasks, null);
50 static void HandleExceptions (IEnumerable<Task> tasks, ParallelLoopState.ExternalInfos infos)
52 List<Exception> exs = new List<Exception> ();
53 foreach (Task t in tasks) {
54 if (t.Exception != null && !(t.Exception is TaskCanceledException))
55 exs.Add (t.Exception);
60 infos.IsExceptional = true;
62 throw new AggregateException (exs);
66 static void InitTasks (Task[] tasks, Action action, int count)
68 InitTasks (tasks, count, () => Task.Factory.StartNew (action, TaskCreationOptions.DetachedFromParent));
71 static void InitTasks (Task[] tasks, Action action, int count, TaskScheduler scheduler)
73 InitTasks (tasks, count, () => Task.Factory.StartNew (action, TaskCreationOptions.DetachedFromParent, scheduler));
76 static void InitTasks (Task[] tasks, int count, Func<Task> taskCreator)
78 for (int i = 0; i < count; i++) {
79 tasks [i] = taskCreator ();
84 public static ParallelLoopResult For (int from, int to, Action<int> action)
86 return For (from, to, null, action);
89 public static ParallelLoopResult For (int from, int to, Action<int, ParallelLoopState> action)
91 return For (from, to, null, action);
94 public static ParallelLoopResult For (int from, int to, ParallelOptions options, Action<int> action)
96 return For (from, to, options, (index, state) => action (index));
99 public static ParallelLoopResult For (int from, int to, ParallelOptions options, Action<int, ParallelLoopState> action)
101 return For<object> (from, to, options, null, (i, s, l) => { action (i, s); return null; }, null);
104 public static ParallelLoopResult For<TLocal> (int from, int to, Func<TLocal> init,
105 Func<int, ParallelLoopState, TLocal, TLocal> action, Action<TLocal> destruct)
107 return For<TLocal> (from, to, null, init, action, destruct);
111 public static ParallelLoopResult For<TLocal> (int from, int to, ParallelOptions options,
113 Func<int, ParallelLoopState, TLocal, TLocal> action,
114 Action<TLocal> destruct)
117 throw new ArgumentNullException ("action");
119 // Number of task to be launched (normally == Env.ProcessorCount)
120 int num = Math.Min (GetBestWorkerNumber (),
121 options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
122 // Integer range that each task process
123 int step = Math.Min (5, (to - from) / num);
127 throw new NotImplementedException ();
129 // Each worker put the indexes it's responsible for here
130 // so that other worker may steal if they starve.
131 ConcurrentBag<int> bag = new ConcurrentBag<int> ();
132 Task[] tasks = new Task [num];
133 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
135 int currentIndex = from;
137 Action workerMethod = delegate {
139 TLocal local = (init == null) ? default (TLocal) : init ();
141 ParallelLoopState state = new ParallelLoopState (tasks, infos);
144 while ((index = Interlocked.Add (ref currentIndex, step) - step) < to) {
145 if (infos.IsStopped.Value)
148 if (options != null && options.CancellationToken.IsCancellationRequested) {
153 for (int i = index; i < to && i < index + step; i++)
156 for (int i = index; i < to && i < index + step && bag.TryTake (out actual); i++) {
157 if (infos.IsStopped.Value)
160 if (options != null && options.CancellationToken.IsCancellationRequested) {
165 if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > actual)
168 state.CurrentIteration = actual;
169 local = action (actual, state, local);
173 while (bag.TryTake (out actual)) {
174 if (infos.IsStopped.Value)
177 if (options != null && options.CancellationToken.IsCancellationRequested) {
182 if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > actual)
185 state.CurrentIteration = actual;
186 local = action (actual, state, local);
189 if (destruct != null)
194 if (options != null && options.TaskScheduler != null)
195 InitTasks (tasks, workerMethod, num, options.TaskScheduler);
197 InitTasks (tasks, workerMethod, num);
200 Task.WaitAll (tasks);
202 HandleExceptions (tasks, infos);
205 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped.Value || infos.IsExceptional));
213 static ParallelLoopResult ForEach<TSource, TLocal> (Func<int, IList<IEnumerator<TSource>>> enumerable, ParallelOptions options,
214 Func<TLocal> init, Func<TSource, ParallelLoopState, TLocal, TLocal> action,
215 Action<TLocal> destruct)
217 int num = Math.Min (GetBestWorkerNumber (),
218 options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
220 Task[] tasks = new Task[num];
221 ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
223 throw new NotImplementedException ();
225 ConcurrentBag<TSource> bag = new ConcurrentBag<TSource> ();
226 const int bagCount = 5;
228 IList<IEnumerator<TSource>> slices = enumerable (num);
231 Action workerMethod = delegate {
232 IEnumerator<TSource> slice = slices[Interlocked.Increment (ref sliceIndex) - 1];
234 TLocal local = (init != null) ? init () : default (TLocal);
235 ParallelLoopState state = new ParallelLoopState (tasks, infos);
242 if (infos.IsStopped.Value)
245 if (options != null && options.CancellationToken.IsCancellationRequested) {
250 for (int i = 0; i < bagCount && (cont = slice.MoveNext ()); i++) {
251 bag.Add (slice.Current);
254 for (int i = 0; i < bagCount && bag.TryTake (out element); i++) {
255 if (infos.IsStopped.Value)
258 if (options != null && options.CancellationToken.IsCancellationRequested) {
263 local = action (element, state, local);
267 while (bag.TryTake (out element)) {
268 if (infos.IsStopped.Value)
271 if (options != null && options.CancellationToken.IsCancellationRequested) {
276 local = action (element, state, local);
279 if (destruct != null)
284 if (options != null && options.TaskScheduler != null)
285 InitTasks (tasks, workerMethod, num, options.TaskScheduler);
287 InitTasks (tasks, workerMethod, num);
290 Task.WaitAll (tasks);
292 HandleExceptions (tasks, infos);
295 return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped.Value || infos.IsExceptional));
299 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable, Action<TSource> action)
301 return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
302 (e, s, l) => { action (e); return null; }, null);
305 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable, Action<TSource, ParallelLoopState> action)
307 return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
308 (e, s, l) => { action (e, s); return null; }, null);
311 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable,
312 Action<TSource, ParallelLoopState, long> action)
314 return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
315 (e, s, l) => { action (e, s, -1); return null; }, null);
318 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
319 Action<TSource, ParallelLoopState> body)
321 return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, l) => { body (e, s); return null; }, null);
324 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source,
325 Action<TSource, ParallelLoopState, long> body)
328 return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, i, l) => { body (e, s, i); return null; }, null);
331 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
332 Action<TSource> body)
335 return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, l) => { body (e); return null; }, null);
338 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
339 Action<TSource> body)
341 return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions, null,
342 (e, s, l) => { body (e); return null; }, null);
345 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
346 Action<TSource, ParallelLoopState> body)
348 return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions, null,
349 (e, s, l) => { body (e, s); return null; }, null);
352 public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
353 Action<TSource, ParallelLoopState, long> body)
355 return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions,
356 null, (e, s, i, l) => { body (e, s, i); return null; }, null);
359 public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
360 Action<TSource, ParallelLoopState, long> body)
363 return ForEach<TSource, object> (source, parallelOptions, null, (e, s, i, l) => { body (e, s, i); return null; }, null);
366 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
367 Action<TSource> body)
369 return ForEach<TSource, object> (source, parallelOptions, null, (e, s, l) => {body (e); return null; }, null);
372 public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
373 Action<TSource, ParallelLoopState> body)
375 return ForEach<TSource, object> (source, parallelOptions, null, (e, s, l) => { body (e, s); return null; }, null);
378 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
379 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
380 Action<TLocal> localFinally)
382 return ForEach<TSource, TLocal> ((Partitioner<TSource>)Partitioner.Create (source), null, localInit, body, localFinally);
385 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
386 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
387 Action<TLocal> localFinally)
389 return ForEach<TSource, TLocal> (Partitioner.Create (source), null, localInit, body, localFinally);
392 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, Func<TLocal> localInit,
393 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
394 Action<TLocal> localFinally)
396 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
399 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, Func<TLocal> localInit,
400 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
401 Action<TLocal> localFinally)
403 return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
406 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
407 Func<TLocal> localInit,
408 Func<TSource, ParallelLoopState, TLocal, TLocal> body,
409 Action<TLocal> localFinally)
411 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
414 public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
415 Func<TLocal> localInit,
416 Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
417 Action<TLocal> localFinally)
419 return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
422 public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> enumerable, ParallelOptions options,
424 Func<TSource, ParallelLoopState, TLocal, TLocal> action,
425 Action<TLocal> destruct)
427 return ForEach<TSource, TLocal> (enumerable.GetPartitions, options, init, action, destruct);
430 public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> enumerable, ParallelOptions options,
432 Func<TSource, ParallelLoopState, long, TLocal, TLocal> action,
433 Action<TLocal> destruct)
435 return ForEach<KeyValuePair<long, TSource>, TLocal> (enumerable.GetOrderablePartitions, options,
436 init, (e, s, l) => action (e.Value, s, e.Key, l), destruct);
440 /* Disabled as this is an API addition
442 public static void While (Func<bool> predicate, Action body)
445 throw new ArgumentNullException ("body");
446 if (predicate == null)
447 throw new ArgumentNullException ("predicate");
449 int num = GetBestWorkerNumber ();
451 Task[] tasks = new Task [num];
453 Action action = delegate {
458 InitTasks (tasks, action, num);
459 Task.WaitAll (tasks);
460 HandleExceptions (tasks);
467 public static void Invoke (params Action[] actions)
470 throw new ArgumentNullException ("actions");
472 Invoke (actions, (Action a) => Task.Factory.StartNew (a));
475 public static void Invoke (ParallelOptions parallelOptions, params Action[] actions)
477 if (parallelOptions == null)
478 throw new ArgumentNullException ("parallelOptions");
480 throw new ArgumentNullException ("actions");
482 Invoke (actions, (Action a) => Task.Factory.StartNew (a, TaskCreationOptions.None, parallelOptions.TaskScheduler));
485 static void Invoke (Action[] actions, Func<Action, Task> taskCreator)
487 if (actions.Length == 0)
488 throw new ArgumentException ("actions is empty");
490 // Execute it directly
491 if (actions.Length == 1 && actions[0] != null)
494 bool shouldThrow = false;
495 Task[] ts = Array.ConvertAll (actions, delegate (Action a) {
501 return taskCreator (a);
505 throw new ArgumentException ("One action in actions is null", "actions");
510 HandleExceptions (ts);
515 #region SpawnBestNumber, used by PLinq
516 internal static Task[] SpawnBestNumber (Action action, Action callback)
518 return SpawnBestNumber (action, -1, callback);
521 internal static Task[] SpawnBestNumber (Action action, int dop, Action callback)
523 return SpawnBestNumber (action, dop, false, callback);
526 internal static Task[] SpawnBestNumber (Action action, int dop, bool wait, Action callback)
528 // Get the optimum amount of worker to create
529 int num = dop == -1 ? (wait ? GetBestWorkerNumber () + 1 : GetBestWorkerNumber ()) : dop;
532 CountdownEvent evt = new CountdownEvent (num);
533 Task[] tasks = new Task [num];
534 for (int i = 0; i < num; i++) {
535 tasks [i] = Task.Factory.StartNew (() => {
538 if (callback != null && evt.IsSet)
543 // If explicitely told, wait for all workers to complete
544 // and thus let main thread participate in the processing
546 Task.WaitAll (tasks);