Parallel.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Parallel.cs
  2. //
  3. // Copyright (c) 2008 Jérémie "Garuma" Laval
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. //
  24. #if NET_4_0
  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. if ((step = (to - from) / num) < 5) {
  47. step = 5;
  48. num = (to - from) / 5;
  49. if (num < 1)
  50. num = 1;
  51. }
  52. return num;
  53. }
  54. static void HandleExceptions (IEnumerable<Task> tasks)
  55. {
  56. HandleExceptions (tasks, null);
  57. }
  58. static void HandleExceptions (IEnumerable<Task> tasks, ParallelLoopState.ExternalInfos infos)
  59. {
  60. List<Exception> exs = new List<Exception> ();
  61. foreach (Task t in tasks) {
  62. if (t.Exception != null)
  63. exs.Add (t.Exception);
  64. }
  65. if (exs.Count > 0) {
  66. if (infos != null)
  67. infos.IsExceptional = true;
  68. throw new AggregateException (exs);
  69. }
  70. }
  71. static void InitTasks (Task[] tasks, int count, Action action, ParallelOptions options)
  72. {
  73. TaskCreationOptions creation = TaskCreationOptions.LongRunning;
  74. for (int i = 0; i < count; i++) {
  75. if (options == null)
  76. tasks [i] = Task.Factory.StartNew (action, creation);
  77. else
  78. tasks [i] = Task.Factory.StartNew (action, options.CancellationToken, creation, options.TaskScheduler);
  79. }
  80. }
  81. #region For
  82. public static ParallelLoopResult For (int from, int to, Action<int> action)
  83. {
  84. return For (from, to, ParallelOptions.Default, action);
  85. }
  86. public static ParallelLoopResult For (int from, int to, Action<int, ParallelLoopState> action)
  87. {
  88. return For (from, to, ParallelOptions.Default, action);
  89. }
  90. public static ParallelLoopResult For (int from, int to, ParallelOptions options, Action<int> action)
  91. {
  92. return For (from, to, options, (index, state) => action (index));
  93. }
  94. public static ParallelLoopResult For (int from, int to, ParallelOptions options, Action<int, ParallelLoopState> action)
  95. {
  96. return For<object> (from, to, options, () => null, (i, s, l) => { action (i, s); return null; }, _ => {});
  97. }
  98. public static ParallelLoopResult For<TLocal> (int from,
  99. int to,
  100. Func<TLocal> init,
  101. Func<int, ParallelLoopState, TLocal, TLocal> action,
  102. Action<TLocal> destruct)
  103. {
  104. return For<TLocal> (from, to, ParallelOptions.Default, init, action, destruct);
  105. }
  106. public static ParallelLoopResult For<TLocal> (int from,
  107. int to,
  108. ParallelOptions options,
  109. Func<TLocal> init,
  110. Func<int, ParallelLoopState, TLocal, TLocal> action,
  111. Action<TLocal> destruct)
  112. {
  113. if (action == null)
  114. throw new ArgumentNullException ("action");
  115. if (init == null)
  116. throw new ArgumentNullException ("localInit");
  117. if (destruct == null)
  118. throw new ArgumentNullException ("localFinally");
  119. if (options == null)
  120. throw new ArgumentNullException ("options");
  121. if (from >= to)
  122. return new ParallelLoopResult (null, true);
  123. // Number of task to be launched (normally == Env.ProcessorCount)
  124. int step;
  125. int num = GetBestWorkerNumber (from, to, options, out step);
  126. Task[] tasks = new Task [num];
  127. StealRange[] ranges = new StealRange[num];
  128. for (int i = 0; i < num; i++)
  129. ranges[i] = new StealRange (from, i, step);
  130. ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
  131. int currentIndex = -1;
  132. Action workerMethod = delegate {
  133. int localWorker = Interlocked.Increment (ref currentIndex);
  134. StealRange range = ranges[localWorker];
  135. int index = range.Actual;
  136. int stopIndex = localWorker + 1 == num ? to : Math.Min (to, index + step);
  137. TLocal local = init ();
  138. ParallelLoopState state = new ParallelLoopState (infos);
  139. CancellationToken token = options.CancellationToken;
  140. try {
  141. for (int i = index; i < stopIndex; range.Actual = ++i) {
  142. if (infos.IsStopped)
  143. return;
  144. token.ThrowIfCancellationRequested ();
  145. if (infos.LowestBreakIteration != null && infos.LowestBreakIteration > i)
  146. return;
  147. state.CurrentIteration = i;
  148. local = action (i, state, local);
  149. if (i >= stopIndex - range.Stolen)
  150. break;
  151. }
  152. // Try to steal from our right neighbor (cyclic)
  153. int len = num + localWorker;
  154. for (int sIndex = localWorker + 1; sIndex < len; ++sIndex) {
  155. int extWorker = sIndex % num;
  156. range = ranges[extWorker];
  157. stopIndex = extWorker + 1 == num ? to : Math.Min (to, from + (extWorker + 1) * step);
  158. int stolen;
  159. do {
  160. stolen = range.Stolen;
  161. if (stopIndex - stolen > range.Actual)
  162. goto next;
  163. } while (Interlocked.CompareExchange (ref range.Stolen, stolen + 1, stolen) != stolen);
  164. stolen = stopIndex - stolen - 1;
  165. if (stolen > range.Actual)
  166. local = action (stolen, state, local);
  167. next:
  168. continue;
  169. }
  170. } finally {
  171. destruct (local);
  172. }
  173. };
  174. InitTasks (tasks, num, workerMethod, options);
  175. try {
  176. Task.WaitAll (tasks);
  177. } catch {
  178. HandleExceptions (tasks, infos);
  179. }
  180. return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
  181. }
  182. class StealRange
  183. {
  184. public int Stolen;
  185. public int Actual;
  186. public StealRange (int from, int i, int step)
  187. {
  188. Actual = from + i * step;
  189. }
  190. }
  191. #endregion
  192. #region Foreach
  193. static ParallelLoopResult ForEach<TSource, TLocal> (Func<int, IList<IEnumerator<TSource>>> enumerable, ParallelOptions options,
  194. Func<TLocal> init, Func<TSource, ParallelLoopState, TLocal, TLocal> action,
  195. Action<TLocal> destruct)
  196. {
  197. int num = Math.Min (GetBestWorkerNumber (),
  198. options != null && options.MaxDegreeOfParallelism != -1 ? options.MaxDegreeOfParallelism : int.MaxValue);
  199. Task[] tasks = new Task[num];
  200. ParallelLoopState.ExternalInfos infos = new ParallelLoopState.ExternalInfos ();
  201. SimpleConcurrentBag<TSource> bag = new SimpleConcurrentBag<TSource> (num);
  202. const int bagCount = 5;
  203. IList<IEnumerator<TSource>> slices = enumerable (num);
  204. int sliceIndex = 0;
  205. Func<ParallelLoopState, bool> cancellationTokenTest = (s) => {
  206. if (options != null && options.CancellationToken.IsCancellationRequested) {
  207. s.Stop ();
  208. return true;
  209. }
  210. return false;
  211. };
  212. Action workerMethod = delegate {
  213. IEnumerator<TSource> slice = slices[Interlocked.Increment (ref sliceIndex) - 1];
  214. TLocal local = (init != null) ? init () : default (TLocal);
  215. ParallelLoopState state = new ParallelLoopState (infos);
  216. int workIndex = bag.GetNextIndex ();
  217. try {
  218. bool cont = true;
  219. TSource element;
  220. while (cont) {
  221. if (infos.IsStopped)
  222. return;
  223. if (cancellationTokenTest (state))
  224. return;
  225. for (int i = 0; i < bagCount && (cont = slice.MoveNext ()); i++) {
  226. bag.Add (workIndex, slice.Current);
  227. }
  228. for (int i = 0; i < bagCount && bag.TryTake (workIndex, out element); i++) {
  229. if (infos.IsStopped)
  230. return;
  231. if (cancellationTokenTest (state))
  232. return;
  233. local = action (element, state, local);
  234. }
  235. }
  236. while (bag.TrySteal (workIndex, out element)) {
  237. if (infos.IsStopped)
  238. return;
  239. if (cancellationTokenTest (state))
  240. return;
  241. local = action (element, state, local);
  242. }
  243. } finally {
  244. if (destruct != null)
  245. destruct (local);
  246. }
  247. };
  248. InitTasks (tasks, num, workerMethod, options);
  249. try {
  250. Task.WaitAll (tasks);
  251. } catch {
  252. HandleExceptions (tasks, infos);
  253. }
  254. return new ParallelLoopResult (infos.LowestBreakIteration, !(infos.IsStopped || infos.IsExceptional));
  255. }
  256. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable, Action<TSource> action)
  257. {
  258. return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
  259. (e, s, l) => { action (e); return null; }, null);
  260. }
  261. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable, Action<TSource, ParallelLoopState> action)
  262. {
  263. return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
  264. (e, s, l) => { action (e, s); return null; }, null);
  265. }
  266. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> enumerable,
  267. Action<TSource, ParallelLoopState, long> action)
  268. {
  269. return ForEach<TSource, object> (Partitioner.Create (enumerable), ParallelOptions.Default, null,
  270. (e, s, l) => { action (e, s, -1); return null; }, null);
  271. }
  272. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
  273. Action<TSource, ParallelLoopState> body)
  274. {
  275. return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, l) => { body (e, s); return null; }, null);
  276. }
  277. public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source,
  278. Action<TSource, ParallelLoopState, long> body)
  279. {
  280. return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, i, l) => { body (e, s, i); return null; }, null);
  281. }
  282. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source,
  283. Action<TSource> body)
  284. {
  285. return ForEach<TSource, object> (source, ParallelOptions.Default, null, (e, s, l) => { body (e); return null; }, null);
  286. }
  287. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  288. Action<TSource> body)
  289. {
  290. return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions, null,
  291. (e, s, l) => { body (e); return null; }, null);
  292. }
  293. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  294. Action<TSource, ParallelLoopState> body)
  295. {
  296. return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions, null,
  297. (e, s, l) => { body (e, s); return null; }, null);
  298. }
  299. public static ParallelLoopResult ForEach<TSource> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  300. Action<TSource, ParallelLoopState, long> body)
  301. {
  302. return ForEach<TSource, object> (Partitioner.Create (source), parallelOptions,
  303. null, (e, s, i, l) => { body (e, s, i); return null; }, null);
  304. }
  305. public static ParallelLoopResult ForEach<TSource> (OrderablePartitioner<TSource> source, ParallelOptions parallelOptions,
  306. Action<TSource, ParallelLoopState, long> body)
  307. {
  308. return ForEach<TSource, object> (source, parallelOptions, null, (e, s, i, l) => { body (e, s, i); return null; }, null);
  309. }
  310. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
  311. Action<TSource> body)
  312. {
  313. return ForEach<TSource, object> (source, parallelOptions, null, (e, s, l) => {body (e); return null; }, null);
  314. }
  315. public static ParallelLoopResult ForEach<TSource> (Partitioner<TSource> source, ParallelOptions parallelOptions,
  316. Action<TSource, ParallelLoopState> body)
  317. {
  318. return ForEach<TSource, object> (source, parallelOptions, null, (e, s, l) => { body (e, s); return null; }, null);
  319. }
  320. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
  321. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  322. Action<TLocal> localFinally)
  323. {
  324. return ForEach<TSource, TLocal> ((Partitioner<TSource>)Partitioner.Create (source), null, localInit, body, localFinally);
  325. }
  326. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, Func<TLocal> localInit,
  327. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  328. Action<TLocal> localFinally)
  329. {
  330. return ForEach<TSource, TLocal> (Partitioner.Create (source), null, localInit, body, localFinally);
  331. }
  332. public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> source, Func<TLocal> localInit,
  333. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  334. Action<TLocal> localFinally)
  335. {
  336. return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
  337. }
  338. public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> source, Func<TLocal> localInit,
  339. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  340. Action<TLocal> localFinally)
  341. {
  342. return ForEach<TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally);
  343. }
  344. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  345. Func<TLocal> localInit,
  346. Func<TSource, ParallelLoopState, TLocal, TLocal> body,
  347. Action<TLocal> localFinally)
  348. {
  349. return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
  350. }
  351. public static ParallelLoopResult ForEach<TSource, TLocal> (IEnumerable<TSource> source, ParallelOptions parallelOptions,
  352. Func<TLocal> localInit,
  353. Func<TSource, ParallelLoopState, long, TLocal, TLocal> body,
  354. Action<TLocal> localFinally)
  355. {
  356. return ForEach<TSource, TLocal> (Partitioner.Create (source), parallelOptions, localInit, body, localFinally);
  357. }
  358. public static ParallelLoopResult ForEach<TSource, TLocal> (Partitioner<TSource> enumerable, ParallelOptions options,
  359. Func<TLocal> init,
  360. Func<TSource, ParallelLoopState, TLocal, TLocal> action,
  361. Action<TLocal> destruct)
  362. {
  363. return ForEach<TSource, TLocal> (enumerable.GetPartitions, options, init, action, destruct);
  364. }
  365. public static ParallelLoopResult ForEach<TSource, TLocal> (OrderablePartitioner<TSource> enumerable, ParallelOptions options,
  366. Func<TLocal> init,
  367. Func<TSource, ParallelLoopState, long, TLocal, TLocal> action,
  368. Action<TLocal> destruct)
  369. {
  370. return ForEach<KeyValuePair<long, TSource>, TLocal> (enumerable.GetOrderablePartitions, options,
  371. init, (e, s, l) => action (e.Value, s, e.Key, l), destruct);
  372. }
  373. #endregion
  374. #region Invoke
  375. public static void Invoke (params Action[] actions)
  376. {
  377. if (actions == null)
  378. throw new ArgumentNullException ("actions");
  379. Invoke (actions, (Action a) => Task.Factory.StartNew (a));
  380. }
  381. public static void Invoke (ParallelOptions parallelOptions, params Action[] actions)
  382. {
  383. if (parallelOptions == null)
  384. throw new ArgumentNullException ("parallelOptions");
  385. if (actions == null)
  386. throw new ArgumentNullException ("actions");
  387. Invoke (actions, (Action a) => Task.Factory.StartNew (a, parallelOptions.CancellationToken, TaskCreationOptions.None, parallelOptions.TaskScheduler));
  388. }
  389. static void Invoke (Action[] actions, Func<Action, Task> taskCreator)
  390. {
  391. if (actions.Length == 0)
  392. throw new ArgumentException ("actions is empty");
  393. // Execute it directly
  394. if (actions.Length == 1 && actions[0] != null)
  395. actions[0] ();
  396. bool shouldThrow = false;
  397. Task[] ts = Array.ConvertAll (actions, delegate (Action a) {
  398. if (a == null) {
  399. shouldThrow = true;
  400. return null;
  401. }
  402. return taskCreator (a);
  403. });
  404. if (shouldThrow)
  405. throw new ArgumentException ("One action in actions is null", "actions");
  406. try {
  407. Task.WaitAll (ts);
  408. } catch {
  409. HandleExceptions (ts);
  410. }
  411. }
  412. #endregion
  413. #region SpawnBestNumber, used by PLinq
  414. internal static Task[] SpawnBestNumber (Action action, Action callback)
  415. {
  416. return SpawnBestNumber (action, -1, callback);
  417. }
  418. internal static Task[] SpawnBestNumber (Action action, int dop, Action callback)
  419. {
  420. return SpawnBestNumber (action, dop, false, callback);
  421. }
  422. internal static Task[] SpawnBestNumber (Action action, int dop, bool wait, Action callback)
  423. {
  424. // Get the optimum amount of worker to create
  425. int num = dop == -1 ? (wait ? GetBestWorkerNumber () + 1 : GetBestWorkerNumber ()) : dop;
  426. // Initialize worker
  427. CountdownEvent evt = new CountdownEvent (num);
  428. Task[] tasks = new Task [num];
  429. for (int i = 0; i < num; i++) {
  430. tasks [i] = Task.Factory.StartNew (() => {
  431. action ();
  432. evt.Signal ();
  433. if (callback != null && evt.IsSet)
  434. callback ();
  435. });
  436. }
  437. // If explicitely told, wait for all workers to complete
  438. // and thus let main thread participate in the processing
  439. if (wait)
  440. Task.WaitAll (tasks);
  441. return tasks;
  442. }
  443. #endregion
  444. }
  445. }
  446. #endif