Parallel.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. #if NET_4_0
  2. // Parallel.cs
  3. //
  4. // Copyright (c) 2008 Jérémie "Garuma" Laval
  5. //
  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:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  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
  22. // THE SOFTWARE.
  23. //
  24. //
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Collections.Concurrent;
  28. using System.Threading;
  29. namespace System.Threading.Tasks
  30. {
  31. public static class Parallel
  32. {
  33. internal static int GetBestWorkerNumber ()
  34. {
  35. return GetBestWorkerNumber (TaskScheduler.Current);
  36. }
  37. internal static int GetBestWorkerNumber (TaskScheduler scheduler)
  38. {
  39. return scheduler.MaximumConcurrencyLevel;
  40. }
  41. static int GetBestWorkerNumber (int from, int to, ParallelOptions options, out int step)
  42. {
  43. int num = Math.Min (GetBestWorkerNumber (),
  44. options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
  45. // Integer range that each task process
  46. step = Math.Min (5, (to - from) / num);
  47. if (step <= 0)
  48. step = 1;
  49. return num;
  50. }
  51. static void HandleExceptions (IEnumerable<Task> tasks)
  52. {
  53. HandleExceptions (tasks, null);
  54. }
  55. static void HandleExceptions (IEnumerable<Task> tasks, ParallelLoopState.ExternalInfos infos)
  56. {
  57. List<Exception> exs = new List<Exception> ();
  58. foreach (Task t in tasks) {
  59. if (t.Exception != null)
  60. exs.Add (t.Exception);
  61. }
  62. if (exs.Count > 0) {
  63. if (infos != null)
  64. infos.IsExceptional = true;
  65. throw new AggregateException (exs);
  66. }
  67. }
  68. static void InitTasks (Task[] tasks, int count, Action action, ParallelOptions options)
  69. {
  70. TaskCreationOptions creation = TaskCreationOptions.LongRunning;
  71. for (int i = 0; i < count; i++) {
  72. if (options == null)
  73. tasks [i] = Task.Factory.StartNew (action, creation);
  74. else
  75. tasks [i] = Task.Factory.StartNew (action, options.CancellationToken, creation, options.TaskScheduler);
  76. }
  77. }
  78. #region For
  79. public static ParallelLoopResult For (int from, int to, Action<int> action)
  80. {
  81. return For (from, to, null, action);
  82. }
  83. public static ParallelLoopResult For (int from, int to, Action<int, ParallelLoopState> action)
  84. {
  85. return For (from, to, null, action);
  86. }
  87. public static ParallelLoopResult For (int from, int to, ParallelOptions options, Action<int> action)
  88. {
  89. return For (from, to, options, (index, state) => action (index));
  90. }
  91. public static ParallelLoopResult For (int from, int to, ParallelOptions options, Action<int, ParallelLoopState> action)
  92. {
  93. return For<object> (from, to, options, null, (i, s, l) => { action (i, s); return null; }, null);
  94. }
  95. public static ParallelLoopResult For<TLocal> (int from, int to, Func<TLocal> init,
  96. Func<int, ParallelLoopState, TLocal, TLocal> action, Action<TLocal> destruct)
  97. {
  98. return For<TLocal> (from, to, null, init, action, destruct);
  99. }
  100. public static ParallelLoopResult For<TLocal> (int from, int to, ParallelOptions options,
  101. Func<TLocal> init,
  102. Func<int, ParallelLoopState, TLocal, TLocal> action,
  103. Action<TLocal> destruct)
  104. {
  105. if (action == null)
  106. throw new ArgumentNullException ("action");
  107. // Number of task to be launched (normally == Env.ProcessorCount)
  108. int step;
  109. int num = GetBestWorkerNumber (from, to, options, out step);
  110. // Each worker put the indexes it's responsible for here
  111. // so that other worker may steal if they starve.
  112. SimpleConcurrentBag<int> bag = new SimpleConcurrentBag<int> (num);
  113. Task[] tasks = new Task [num];
  114. ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
  115. Func<ParallelLoopState, bool> cancellationTokenTest = (s) => {
  116. if (options != null && options.CancellationToken.IsCancellationRequested) {
  117. s.Stop ();
  118. return true;
  119. }
  120. return false;
  121. };
  122. Func<int, bool> breakTest = (i) => infos.LowestBreakIteration != null && infos.LowestBreakIteration > i;
  123. int currentIndex = from;
  124. Action workerMethod = delegate {
  125. int index, actual;
  126. TLocal local = (init == null) ? default (TLocal) : init ();
  127. ParallelLoopState state = new ParallelLoopState (infos);
  128. int workIndex = bag.GetNextIndex ();
  129. try {
  130. while (currentIndex < to && (index = Interlocked.Add (ref currentIndex, step) - step) < to) {
  131. if (infos.IsStopped.Value)
  132. return;
  133. if (cancellationTokenTest (state))
  134. return;
  135. for (int i = index; i < to && i < index + step; i++)
  136. bag.Add (workIndex, i);
  137. for (int i = index; i < to && i < index + step && bag.TryTake (workIndex, out actual); i++) {
  138. if (infos.IsStopped.Value)
  139. return;
  140. if (cancellationTokenTest (state))
  141. return;
  142. if (breakTest (actual))
  143. return;
  144. state.CurrentIteration = actual;
  145. local = action (actual, state, local);
  146. }
  147. }
  148. while (bag.TrySteal (workIndex, out actual)) {
  149. if (infos.IsStopped.Value)
  150. return;
  151. if (cancellationTokenTest (state))
  152. return;
  153. if (breakTest (actual))
  154. continue;
  155. state.CurrentIteration = actual;
  156. local = action (actual, state, local);
  157. }
  158. } finally {
  159. if (destruct != null)
  160. destruct (local);
  161. }
  162. };
  163. InitTasks (tasks, num, workerMethod, options);
  164. try {
  165. Task.WaitAll (tasks);
  166. } catch {
  167. HandleExceptions (tasks, infos);
  168. }
  169. return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped.Value || infos.IsExceptional));
  170. }
  171. #endregion
  172. #region Foreach
  173. static ParallelLoopResult ForEach<TSource, TLocal> (Func<int, IList<IEnumerator<TSource>>> enumerable, ParallelOptions options,
  174. Func<TLocal> init, Func<TSource, ParallelLoopState, TLocal, TLocal> action,
  175. Action<TLocal> destruct)
  176. {
  177. int num = Math.Min (GetBestWorkerNumber (),
  178. options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
  179. Task[] tasks = new Task[num];
  180. ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
  181. SimpleConcurrentBag<TSource> bag = new SimpleConcurrentBag<TSource> (num);
  182. const int bagCount = 5;
  183. IList<IEnumerator<TSource>> slices = enumerable (num);
  184. int sliceIndex = 0;
  185. Func<ParallelLoopState, bool> cancellationTokenTest = (s) => {
  186. if (options != null && options.CancellationToken.IsCancellationRequested) {
  187. s.Stop ();
  188. return true;
  189. }
  190. return false;
  191. };
  192. Action workerMethod = delegate {
  193. IEnumerator<TSource> slice = slices[Interlocked.Increment (ref sliceIndex) - 1];
  194. TLocal local = (init != null) ? init () : default (TLocal);
  195. ParallelLoopState state = new ParallelLoopState (infos);
  196. int workIndex = bag.GetNextIndex ();
  197. try {
  198. bool cont = true;
  199. TSource element;
  200. while (cont) {
  201. if (infos.IsStopped.Value)
  202. return;
  203. if (cancellationTokenTest (state))
  204. return;
  205. for (int i = 0; i < bagCount && (cont = slice.MoveNext ()); i++) {
  206. bag.Add (workIndex, slice.Current);
  207. }
  208. for (int i = 0; i < bagCount && bag.TryTake (workIndex, out element); i++) {
  209. if (infos.IsStopped.Value)
  210. return;
  211. if (cancellationTokenTest (state))
  212. return;
  213. local = action (element, state, local);
  214. }
  215. }
  216. while (bag.TrySteal (workIndex, out element)) {
  217. if (infos.IsStopped.Value)
  218. return;
  219. if (cancellationTokenTest (state))
  220. return;
  221. local = action (element, state, local);
  222. }
  223. } finally {
  224. if (destruct != null)
  225. destruct (local);
  226. }
  227. };
  228. InitTasks (tasks, num, workerMethod, options);
  229. try {
  230. Task.WaitAll (tasks);
  231. } catch {
  232. HandleExceptions (tasks, infos);
  233. }
  234. return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped.Value || infos.IsExceptional));
  235. }
  236. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable, Action<TSource> action)
  237. {
  238. return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
  239. (e, s, l) => { action (e); return null; }, null);
  240. }
  241. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable, Action<TSource, ParallelLoopState> action)
  242. {
  243. return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
  244. (e, s, l) => { action (e, s); return null; }, null);
  245. }
  246. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable,
  247. Action<TSource, ParallelLoopState, long> action)
  248. {
  249. return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
  250. (e, s, l) => { action (e, s, -1); return null; }, null);
  251. }
  252. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
  253. Action<TSource, ParallelLoopState> body)
  254. {
  255. return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, l) => { body (e, s); return null; }, null);
  256. }
  257. public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source,
  258. Action<TSource, ParallelLoopState, long> body)
  259. {
  260. return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, i, l) => { body (e, s, i); return null; }, null);
  261. }
  262. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
  263. Action<TSource> body)
  264. {
  265. return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, l) => { body (e); return null; }, null);
  266. }
  267. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  268. Action<TSource> body)
  269. {
  270. return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions, null,
  271. (e, s, l) => { body (e); return null; }, null);
  272. }
  273. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  274. Action<TSource, ParallelLoopState> body)
  275. {
  276. return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions, null,
  277. (e, s, l) => { body (e, s); return null; }, null);
  278. }
  279. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  280. Action<TSource, ParallelLoopState, long> body)
  281. {
  282. return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions,
  283. null, (e, s, i, l) => { body (e, s, i); return null; }, null);
  284. }
  285. public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
  286. Action<TSource, ParallelLoopState, long> body)
  287. {
  288. return ForEach<TSource, object> (source, parallelOptions, null, (e, s, i, l) => { body (e, s, i); return null; }, null);
  289. }
  290. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
  291. Action<TSource> body)
  292. {
  293. return ForEach<TSource, object> (source, parallelOptions, null, (e, s, l) => {body (e); return null; }, null);
  294. }
  295. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
  296. Action<TSource, ParallelLoopState> body)
  297. {
  298. return ForEach<TSource, object> (source, parallelOptions, null, (e, s, l) => { body (e, s); return null; }, null);
  299. }
  300. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
  301. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  302. Action<TLocal> localFinally)
  303. {
  304. return ForEach<TSource, TLocal> ((Partitioner<TSource>)Partitioner.Create (source), null, localInit, body, localFinally);
  305. }
  306. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
  307. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  308. Action<TLocal> localFinally)
  309. {
  310. return ForEach<TSource, TLocal> (Partitioner.Create (source), null, localInit, body, localFinally);
  311. }
  312. public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, Func<TLocal> localInit,
  313. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  314. Action<TLocal> localFinally)
  315. {
  316. return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
  317. }
  318. public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, Func<TLocal> localInit,
  319. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  320. Action<TLocal> localFinally)
  321. {
  322. return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
  323. }
  324. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  325. Func<TLocal> localInit,
  326. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  327. Action<TLocal> localFinally)
  328. {
  329. return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
  330. }
  331. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  332. Func<TLocal> localInit,
  333. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  334. Action<TLocal> localFinally)
  335. {
  336. return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
  337. }
  338. public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> enumerable, ParallelOptions options,
  339. Func<TLocal> init,
  340. Func<TSource, ParallelLoopState, TLocal, TLocal> action,
  341. Action<TLocal> destruct)
  342. {
  343. return ForEach<TSource, TLocal> (enumerable.GetPartitions, options, init, action, destruct);
  344. }
  345. public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> enumerable, ParallelOptions options,
  346. Func<TLocal> init,
  347. Func<TSource, ParallelLoopState, long, TLocal, TLocal> action,
  348. Action<TLocal> destruct)
  349. {
  350. return ForEach<KeyValuePair<long, TSource>, TLocal> (enumerable.GetOrderablePartitions, options,
  351. init, (e, s, l) => action (e.Value, s, e.Key, l), destruct);
  352. }
  353. #endregion
  354. #region Invoke
  355. public static void Invoke (params Action[] actions)
  356. {
  357. if (actions == null)
  358. throw new ArgumentNullException ("actions");
  359. Invoke (actions, (Action a) => Task.Factory.StartNew (a));
  360. }
  361. public static void Invoke (ParallelOptions parallelOptions, params Action[] actions)
  362. {
  363. if (parallelOptions == null)
  364. throw new ArgumentNullException ("parallelOptions");
  365. if (actions == null)
  366. throw new ArgumentNullException ("actions");
  367. Invoke (actions, (Action a) => Task.Factory.StartNew (a, CancellationToken.None, TaskCreationOptions.None, parallelOptions.TaskScheduler));
  368. }
  369. static void Invoke (Action[] actions, Func<Action, Task> taskCreator)
  370. {
  371. if (actions.Length == 0)
  372. throw new ArgumentException ("actions is empty");
  373. // Execute it directly
  374. if (actions.Length == 1 && actions[0] != null)
  375. actions[0] ();
  376. bool shouldThrow = false;
  377. Task[] ts = Array.ConvertAll (actions, delegate (Action a) {
  378. if (a == null) {
  379. shouldThrow = true;
  380. return null;
  381. }
  382. return taskCreator (a);
  383. });
  384. if (shouldThrow)
  385. throw new ArgumentException ("One action in actions is null", "actions");
  386. try {
  387. Task.WaitAll (ts);
  388. } catch {
  389. HandleExceptions (ts);
  390. }
  391. }
  392. #endregion
  393. #region SpawnBestNumber, used by PLinq
  394. internal static Task[] SpawnBestNumber (Action action, Action callback)
  395. {
  396. return SpawnBestNumber (action, -1, callback);
  397. }
  398. internal static Task[] SpawnBestNumber (Action action, int dop, Action callback)
  399. {
  400. return SpawnBestNumber (action, dop, false, callback);
  401. }
  402. internal static Task[] SpawnBestNumber (Action action, int dop, bool wait, Action callback)
  403. {
  404. // Get the optimum amount of worker to create
  405. int num = dop == -1 ? (wait ? GetBestWorkerNumber () + 1 : GetBestWorkerNumber ()) : dop;
  406. // Initialize worker
  407. CountdownEvent evt = new CountdownEvent (num);
  408. Task[] tasks = new Task [num];
  409. for (int i = 0; i < num; i++) {
  410. tasks [i] = Task.Factory.StartNew (() => {
  411. action ();
  412. evt.Signal ();
  413. if (callback != null && evt.IsSet)
  414. callback ();
  415. });
  416. }
  417. // If explicitely told, wait for all workers to complete
  418. // and thus let main thread participate in the processing
  419. if (wait)
  420. Task.WaitAll (tasks);
  421. return tasks;
  422. }
  423. #endregion
  424. }
  425. }
  426. #endif