ParallelExecuter.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. using System;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Collections.Concurrent;
  32. using System.Linq.Parallel.QueryNodes;
  33. namespace System.Linq.Parallel
  34. {
  35. internal static class ParallelExecuter
  36. {
  37. internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode)
  38. {
  39. return CheckQuery<T> (startingNode, false);
  40. }
  41. internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode, bool blocking)
  42. {
  43. return CheckQuery (startingNode, GetBestWorkerNumber (blocking));
  44. }
  45. internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode, int partitionCount)
  46. {
  47. QueryCheckerVisitor visitor = new QueryCheckerVisitor (partitionCount);
  48. startingNode.Visit (visitor);
  49. return visitor.Options;
  50. }
  51. internal static CancellationToken Chain (this CancellationToken self, CancellationTokenSource other)
  52. {
  53. CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource (self, other.Token);
  54. return linked.Token;
  55. }
  56. internal static bool IsOrdered<TSource> (this QueryBaseNode<TSource> source)
  57. {
  58. QueryIsOrderedVisitor visitor = new QueryIsOrderedVisitor ();
  59. source.Visit (visitor);
  60. return visitor.BehindOrderGuard;
  61. }
  62. internal static int GetBestWorkerNumber ()
  63. {
  64. return GetBestWorkerNumber (false);
  65. }
  66. internal static int GetBestWorkerNumber (bool blocking)
  67. {
  68. return blocking && Task.CurrentId == null ? Environment.ProcessorCount + 1 : Environment.ProcessorCount;
  69. }
  70. internal static Task[] Process<TSource, TElement> (QueryBaseNode<TSource> node,
  71. Action<TElement, CancellationToken> call,
  72. Func<QueryBaseNode<TSource>, QueryOptions, IList<IEnumerable<TElement>>> acquisitionFunc,
  73. QueryOptions options)
  74. {
  75. return Process<TSource, TElement> (node, call, acquisitionFunc, null, options);
  76. }
  77. internal static Task[] Process<TSource, TElement> (QueryBaseNode<TSource> node,
  78. Action<TElement, CancellationToken> call,
  79. Func<QueryBaseNode<TSource>, QueryOptions, IList<IEnumerable<TElement>>> acquisitionFunc,
  80. Action endAction,
  81. QueryOptions options)
  82. {
  83. CancellationTokenSource src
  84. = CancellationTokenSource.CreateLinkedTokenSource (options.ImplementerToken, options.Token);
  85. IList<IEnumerable<TElement>> enumerables = acquisitionFunc (node, options);
  86. Task[] tasks = new Task[enumerables.Count];
  87. for (int i = 0; i < tasks.Length; i++) {
  88. int index = i;
  89. tasks[i] = Task.Factory.StartNew (() => {
  90. try {
  91. foreach (TElement item in enumerables[index]) {
  92. if (!CheckTokens (options))
  93. break;
  94. try {
  95. call (item, src.Token);
  96. } catch (OperationCanceledException canceledException) {
  97. if (canceledException.CancellationToken != src.Token)
  98. throw canceledException;
  99. }
  100. if (!CheckTokens (options))
  101. break;
  102. }
  103. } finally {
  104. if (endAction != null)
  105. endAction ();
  106. }
  107. }, options.Token, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning, TaskScheduler.Default);
  108. }
  109. return tasks;
  110. }
  111. static bool CheckTokens (QueryOptions options)
  112. {
  113. // This is from specific operators
  114. if (options.ImplementerToken.IsCancellationRequested)
  115. return false;
  116. if (options.Token.IsCancellationRequested)
  117. throw new OperationCanceledException (options.Token);
  118. return true;
  119. }
  120. internal static void ProcessAndBlock<T> (QueryBaseNode<T> node, Action<T, CancellationToken> call)
  121. {
  122. QueryOptions options = CheckQuery (node, true);
  123. Task[] tasks = Process (node, call, new QueryBaseNodeHelper<T> ().GetEnumerables, options);
  124. Task.WaitAll (tasks, options.Token);
  125. }
  126. internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<T, CancellationToken> call,
  127. Action callback, QueryOptions options)
  128. {
  129. Task[] tasks = Process (node, call, new QueryBaseNodeHelper<T> ().GetEnumerables, options);
  130. if (callback != null)
  131. Task.Factory.ContinueWhenAll (tasks, (_) => callback ());
  132. return () => Task.WaitAll (tasks, options.Token);
  133. }
  134. internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<KeyValuePair<long, T>, CancellationToken> call,
  135. Action endAction,
  136. Action callback, QueryOptions options)
  137. {
  138. Task[] tasks = Process (node, call, new QueryBaseNodeHelper<T> ().GetOrderedEnumerables, endAction, options);
  139. if (callback != null)
  140. Task.Factory.ContinueWhenAll (tasks, (_) => callback ());
  141. return () => Task.WaitAll (tasks, options.Token);
  142. }
  143. internal static void ProcessAndAggregate<T, U> (QueryBaseNode<T> node,
  144. Func<U> seedFunc,
  145. Func<U, T, U> localCall,
  146. Action<IList<U>> call)
  147. {
  148. QueryOptions options = CheckQuery (node, true);
  149. IList<IEnumerable<T>> enumerables = node.GetEnumerables (options);
  150. U[] locals = new U[enumerables.Count];
  151. Task[] tasks = new Task[enumerables.Count];
  152. if (seedFunc != null) {
  153. for (int i = 0; i < locals.Length; i++)
  154. locals[i] = seedFunc ();
  155. }
  156. for (int i = 0; i < tasks.Length; i++) {
  157. var procSlot = new AggregateProcessSlot<T, U> (options,
  158. i,
  159. enumerables[i].GetEnumerator (),
  160. locals,
  161. localCall,
  162. seedFunc);
  163. tasks[i] = Task.Factory.StartNew (procSlot.Process, options.Token);
  164. }
  165. Task.WaitAll (tasks, options.Token);
  166. if (call != null)
  167. call (locals);
  168. }
  169. class AggregateProcessSlot<T, U>
  170. {
  171. readonly QueryOptions options;
  172. readonly int index;
  173. readonly IEnumerator<T> enumerator;
  174. readonly U[] locals;
  175. readonly Func<U, T, U> localCall;
  176. readonly Func<U> seedFunc;
  177. public AggregateProcessSlot (QueryOptions options,
  178. int index,
  179. IEnumerator<T> enumerator,
  180. U[] locals,
  181. Func<U, T, U> localCall,
  182. Func<U> seedFunc)
  183. {
  184. this.options = options;
  185. this.index = index;
  186. this.enumerator = enumerator;
  187. this.locals = locals;
  188. this.localCall = localCall;
  189. this.seedFunc = seedFunc;
  190. }
  191. public void Process ()
  192. {
  193. var token = options.Token;
  194. var implementerToken = options.ImplementerToken;
  195. try {
  196. // Avoid cache thrashing of locals array
  197. var local = locals [index];
  198. if (seedFunc == null) {
  199. if (!enumerator.MoveNext ())
  200. return;
  201. local = (U)(object)enumerator.Current;
  202. }
  203. while (enumerator.MoveNext ()) {
  204. if (implementerToken.IsCancellationRequested)
  205. break;
  206. token.ThrowIfCancellationRequested ();
  207. local = localCall (local, enumerator.Current);
  208. }
  209. locals [index] = local;
  210. } finally {
  211. enumerator.Dispose ();
  212. }
  213. }
  214. }
  215. class QueryBaseNodeHelper<T>
  216. {
  217. internal IList<IEnumerable<T>> GetEnumerables (QueryBaseNode<T> source, QueryOptions options)
  218. {
  219. return source.GetEnumerables (options);
  220. }
  221. internal IList<IEnumerable<KeyValuePair<long,T>>> GetOrderedEnumerables (QueryBaseNode<T> source, QueryOptions options)
  222. {
  223. return source.GetOrderedEnumerables (options);
  224. }
  225. }
  226. }
  227. }