ParallelExecuter.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //
  2. // ParallelExecuter.cs
  3. //
  4. // Author:
  5. // Jérémie "Garuma" Laval <[email protected]>
  6. //
  7. // Copyright (c) 2010 Jérémie "Garuma" Laval
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if NET_4_0
  27. using System;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Collections.Concurrent;
  33. using System.Linq.Parallel.QueryNodes;
  34. namespace System.Linq.Parallel
  35. {
  36. internal static class ParallelExecuter
  37. {
  38. internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode)
  39. {
  40. return CheckQuery<T> (startingNode, false);
  41. }
  42. internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode, bool blocking)
  43. {
  44. return CheckQuery (startingNode, GetBestWorkerNumber (blocking));
  45. }
  46. internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode, int partitionCount)
  47. {
  48. QueryCheckerVisitor visitor = new QueryCheckerVisitor (partitionCount);
  49. startingNode.Visit (visitor);
  50. return visitor.Options;
  51. }
  52. internal static CancellationToken Chain (this CancellationToken self, CancellationTokenSource other)
  53. {
  54. CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource (self, other.Token);
  55. return linked.Token;
  56. }
  57. internal static bool IsOrdered<TSource> (this QueryBaseNode<TSource> source)
  58. {
  59. QueryIsOrderedVisitor visitor = new QueryIsOrderedVisitor ();
  60. source.Visit (visitor);
  61. return visitor.BehindOrderGuard;
  62. }
  63. internal static int GetBestWorkerNumber ()
  64. {
  65. return GetBestWorkerNumber (false);
  66. }
  67. internal static int GetBestWorkerNumber (bool blocking)
  68. {
  69. return blocking && Task.CurrentId == null ? Environment.ProcessorCount + 1 : Environment.ProcessorCount;
  70. }
  71. internal static Task[] Process<TSource, TElement> (QueryBaseNode<TSource> node,
  72. Action<TElement, CancellationToken> call,
  73. Func<QueryBaseNode<TSource>, QueryOptions, IList<IEnumerable<TElement>>> acquisitionFunc,
  74. QueryOptions options)
  75. {
  76. return Process<TSource, TElement> (node, call, acquisitionFunc, null, options);
  77. }
  78. internal static Task[] Process<TSource, TElement> (QueryBaseNode<TSource> node,
  79. Action<TElement, CancellationToken> call,
  80. Func<QueryBaseNode<TSource>, QueryOptions, IList<IEnumerable<TElement>>> acquisitionFunc,
  81. Action endAction,
  82. QueryOptions options)
  83. {
  84. CancellationTokenSource src
  85. = CancellationTokenSource.CreateLinkedTokenSource (options.ImplementerToken, options.Token);
  86. IList<IEnumerable<TElement>> enumerables = acquisitionFunc (node, options);
  87. Task[] tasks = new Task[enumerables.Count];
  88. for (int i = 0; i < tasks.Length; i++) {
  89. int index = i;
  90. tasks[i] = Task.Factory.StartNew (() => {
  91. try {
  92. foreach (TElement item in enumerables[index]) {
  93. // This is from specific operators
  94. if (options.ImplementerToken.IsCancellationRequested)
  95. break;
  96. if (options.Token.IsCancellationRequested)
  97. throw new OperationCanceledException (options.Token);
  98. call (item, src.Token);
  99. }
  100. } finally {
  101. if (endAction != null)
  102. endAction ();
  103. }
  104. }, options.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Default);
  105. }
  106. return tasks;
  107. }
  108. internal static void ProcessAndBlock<T> (QueryBaseNode<T> node, Action<T, CancellationToken> call)
  109. {
  110. QueryOptions options = CheckQuery (node, true);
  111. Task[] tasks = Process (node, call, (n, o) => n.GetEnumerables (o), options);
  112. Task.WaitAll (tasks, options.Token);
  113. }
  114. internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<T, CancellationToken> call,
  115. Action callback, QueryOptions options)
  116. {
  117. Task[] tasks = Process (node, call, (n, o) => n.GetEnumerables (o), options);
  118. if (callback != null)
  119. Task.Factory.ContinueWhenAll (tasks, (_) => callback ());
  120. return () => Task.WaitAll (tasks, options.Token);
  121. }
  122. internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<KeyValuePair<long, T>, CancellationToken> call,
  123. Action endAction,
  124. Action callback, QueryOptions options)
  125. {
  126. Task[] tasks = Process (node, call, (n, o) => n.GetOrderedEnumerables (o), endAction, options);
  127. if (callback != null)
  128. Task.Factory.ContinueWhenAll (tasks, (_) => callback ());
  129. return () => Task.WaitAll (tasks, options.Token);
  130. }
  131. internal static void ProcessAndAggregate<T, U> (QueryBaseNode<T> node,
  132. Func<U> seedFunc,
  133. Func<U, T, U> localCall,
  134. Action<IList<U>> call)
  135. {
  136. QueryOptions options = CheckQuery (node, true);
  137. IList<IEnumerable<T>> enumerables = node.GetEnumerables (options);
  138. U[] locals = new U[enumerables.Count];
  139. Task[] tasks = new Task[enumerables.Count];
  140. if (seedFunc != null) {
  141. for (int i = 0; i < locals.Length; i++)
  142. locals[i] = seedFunc ();
  143. }
  144. for (int i = 0; i < tasks.Length; i++) {
  145. var procSlot = new AggregateProcessSlot<T, U> (options,
  146. i,
  147. enumerables[i].GetEnumerator (),
  148. locals,
  149. localCall,
  150. seedFunc);
  151. tasks[i] = Task.Factory.StartNew (procSlot.Process, options.Token);
  152. }
  153. Task.WaitAll (tasks, options.Token);
  154. if (call != null)
  155. call (locals);
  156. }
  157. class AggregateProcessSlot<T, U>
  158. {
  159. readonly QueryOptions options;
  160. readonly int index;
  161. readonly IEnumerator<T> enumerator;
  162. readonly U[] locals;
  163. readonly Func<U, T, U> localCall;
  164. readonly Func<U> seedFunc;
  165. public AggregateProcessSlot (QueryOptions options,
  166. int index,
  167. IEnumerator<T> enumerator,
  168. U[] locals,
  169. Func<U, T, U> localCall,
  170. Func<U> seedFunc)
  171. {
  172. this.options = options;
  173. this.index = index;
  174. this.enumerator = enumerator;
  175. this.locals = locals;
  176. this.localCall = localCall;
  177. this.seedFunc = seedFunc;
  178. }
  179. public void Process ()
  180. {
  181. var token = options.Token;
  182. var implementerToken = options.ImplementerToken;
  183. try {
  184. if (seedFunc == null) {
  185. if (!enumerator.MoveNext ())
  186. return;
  187. locals[index] = (U)(object)enumerator.Current;
  188. }
  189. while (enumerator.MoveNext ()) {
  190. if (implementerToken.IsCancellationRequested)
  191. break;
  192. token.ThrowIfCancellationRequested ();
  193. locals[index] = localCall (locals[index], enumerator.Current);
  194. }
  195. } finally {
  196. enumerator.Dispose ();
  197. }
  198. }
  199. }
  200. }
  201. }
  202. #endif