ParallelExecuter.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. if (!CheckTokens (options))
  94. break;
  95. try {
  96. call (item, src.Token);
  97. } catch (OperationCanceledException canceledException) {
  98. if (canceledException.CancellationToken != src.Token)
  99. throw canceledException;
  100. }
  101. if (!CheckTokens (options))
  102. break;
  103. }
  104. } finally {
  105. if (endAction != null)
  106. endAction ();
  107. }
  108. }, options.Token, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning, TaskScheduler.Default);
  109. }
  110. return tasks;
  111. }
  112. static bool CheckTokens (QueryOptions options)
  113. {
  114. // This is from specific operators
  115. if (options.ImplementerToken.IsCancellationRequested)
  116. return false;
  117. if (options.Token.IsCancellationRequested)
  118. throw new OperationCanceledException (options.Token);
  119. return true;
  120. }
  121. internal static void ProcessAndBlock<T> (QueryBaseNode<T> node, Action<T, CancellationToken> call)
  122. {
  123. QueryOptions options = CheckQuery (node, true);
  124. Task[] tasks = Process (node, call, new QueryBaseNodeHelper<T> ().GetEnumerables, options);
  125. Task.WaitAll (tasks, options.Token);
  126. }
  127. internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<T, CancellationToken> call,
  128. Action callback, QueryOptions options)
  129. {
  130. Task[] tasks = Process (node, call, new QueryBaseNodeHelper<T> ().GetEnumerables, options);
  131. if (callback != null)
  132. Task.Factory.ContinueWhenAll (tasks, (_) => callback ());
  133. return () => Task.WaitAll (tasks, options.Token);
  134. }
  135. internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<KeyValuePair<long, T>, CancellationToken> call,
  136. Action endAction,
  137. Action callback, QueryOptions options)
  138. {
  139. Task[] tasks = Process (node, call, new QueryBaseNodeHelper<T> ().GetOrderedEnumerables, endAction, options);
  140. if (callback != null)
  141. Task.Factory.ContinueWhenAll (tasks, (_) => callback ());
  142. return () => Task.WaitAll (tasks, options.Token);
  143. }
  144. internal static void ProcessAndAggregate<T, U> (QueryBaseNode<T> node,
  145. Func<U> seedFunc,
  146. Func<U, T, U> localCall,
  147. Action<IList<U>> call)
  148. {
  149. QueryOptions options = CheckQuery (node, true);
  150. IList<IEnumerable<T>> enumerables = node.GetEnumerables (options);
  151. U[] locals = new U[enumerables.Count];
  152. Task[] tasks = new Task[enumerables.Count];
  153. if (seedFunc != null) {
  154. for (int i = 0; i < locals.Length; i++)
  155. locals[i] = seedFunc ();
  156. }
  157. for (int i = 0; i < tasks.Length; i++) {
  158. var procSlot = new AggregateProcessSlot<T, U> (options,
  159. i,
  160. enumerables[i].GetEnumerator (),
  161. locals,
  162. localCall,
  163. seedFunc);
  164. tasks[i] = Task.Factory.StartNew (procSlot.Process, options.Token);
  165. }
  166. Task.WaitAll (tasks, options.Token);
  167. if (call != null)
  168. call (locals);
  169. }
  170. class AggregateProcessSlot<T, U>
  171. {
  172. readonly QueryOptions options;
  173. readonly int index;
  174. readonly IEnumerator<T> enumerator;
  175. readonly U[] locals;
  176. readonly Func<U, T, U> localCall;
  177. readonly Func<U> seedFunc;
  178. public AggregateProcessSlot (QueryOptions options,
  179. int index,
  180. IEnumerator<T> enumerator,
  181. U[] locals,
  182. Func<U, T, U> localCall,
  183. Func<U> seedFunc)
  184. {
  185. this.options = options;
  186. this.index = index;
  187. this.enumerator = enumerator;
  188. this.locals = locals;
  189. this.localCall = localCall;
  190. this.seedFunc = seedFunc;
  191. }
  192. public void Process ()
  193. {
  194. var token = options.Token;
  195. var implementerToken = options.ImplementerToken;
  196. try {
  197. if (seedFunc == null) {
  198. if (!enumerator.MoveNext ())
  199. return;
  200. locals[index] = (U)(object)enumerator.Current;
  201. }
  202. while (enumerator.MoveNext ()) {
  203. if (implementerToken.IsCancellationRequested)
  204. break;
  205. token.ThrowIfCancellationRequested ();
  206. locals[index] = localCall (locals[index], enumerator.Current);
  207. }
  208. } finally {
  209. enumerator.Dispose ();
  210. }
  211. }
  212. }
  213. class QueryBaseNodeHelper<T>
  214. {
  215. internal IList<IEnumerable<T>> GetEnumerables (QueryBaseNode<T> source, QueryOptions options)
  216. {
  217. return source.GetEnumerables (options);
  218. }
  219. internal IList<IEnumerable<KeyValuePair<long,T>>> GetOrderedEnumerables (QueryBaseNode<T> source, QueryOptions options)
  220. {
  221. return source.GetOrderedEnumerables (options);
  222. }
  223. }
  224. }
  225. }
  226. #endif