Parallel.cs 20 KB

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