Parallel.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Threading;
  30. namespace OpenSim.Framework
  31. {
  32. /// <summary>
  33. /// Provides helper methods for parallelizing loops
  34. /// </summary>
  35. public static class Parallel
  36. {
  37. public static readonly int ProcessorCount = System.Environment.ProcessorCount;
  38. /// <summary>
  39. /// Executes a for loop in which iterations may run in parallel
  40. /// </summary>
  41. /// <param name="fromInclusive">The loop will be started at this index</param>
  42. /// <param name="toExclusive">The loop will be terminated before this index is reached</param>
  43. /// <param name="body">Method body to run for each iteration of the loop</param>
  44. public static void For(int fromInclusive, int toExclusive, Action<int> body)
  45. {
  46. For(ProcessorCount, fromInclusive, toExclusive, body);
  47. }
  48. /// <summary>
  49. /// Executes a for loop in which iterations may run in parallel
  50. /// </summary>
  51. /// <param name="threadCount">The number of concurrent execution threads to run</param>
  52. /// <param name="fromInclusive">The loop will be started at this index</param>
  53. /// <param name="toExclusive">The loop will be terminated before this index is reached</param>
  54. /// <param name="body">Method body to run for each iteration of the loop</param>
  55. public static void For(int threadCount, int fromInclusive, int toExclusive, Action<int> body)
  56. {
  57. int counter = threadCount;
  58. AutoResetEvent threadFinishEvent = new AutoResetEvent(false);
  59. Exception exception = null;
  60. --fromInclusive;
  61. for (int i = 0; i < threadCount; i++)
  62. {
  63. Util.FireAndForget(
  64. delegate(object o)
  65. {
  66. int threadIndex = (int)o;
  67. while (exception == null)
  68. {
  69. int currentIndex = Interlocked.Increment(ref fromInclusive);
  70. if (currentIndex >= toExclusive)
  71. break;
  72. try { body(currentIndex); }
  73. catch (Exception ex) { exception = ex; break; }
  74. }
  75. if (Interlocked.Decrement(ref counter) == 0)
  76. threadFinishEvent.Set();
  77. }, i
  78. );
  79. }
  80. threadFinishEvent.WaitOne();
  81. threadFinishEvent.Close();
  82. if (exception != null)
  83. throw new Exception(exception.Message, exception);
  84. }
  85. /// <summary>
  86. /// Executes a foreach loop in which iterations may run in parallel
  87. /// </summary>
  88. /// <typeparam name="T">Object type that the collection wraps</typeparam>
  89. /// <param name="enumerable">An enumerable collection to iterate over</param>
  90. /// <param name="body">Method body to run for each object in the collection</param>
  91. public static void ForEach<T>(IEnumerable<T> enumerable, Action<T> body)
  92. {
  93. ForEach<T>(ProcessorCount, enumerable, body);
  94. }
  95. /// <summary>
  96. /// Executes a foreach loop in which iterations may run in parallel
  97. /// </summary>
  98. /// <typeparam name="T">Object type that the collection wraps</typeparam>
  99. /// <param name="threadCount">The number of concurrent execution threads to run</param>
  100. /// <param name="enumerable">An enumerable collection to iterate over</param>
  101. /// <param name="body">Method body to run for each object in the collection</param>
  102. public static void ForEach<T>(int threadCount, IEnumerable<T> enumerable, Action<T> body)
  103. {
  104. int counter = threadCount;
  105. AutoResetEvent threadFinishEvent = new AutoResetEvent(false);
  106. IEnumerator<T> enumerator = enumerable.GetEnumerator();
  107. Exception exception = null;
  108. for (int i = 0; i < threadCount; i++)
  109. {
  110. Util.FireAndForget(
  111. delegate(object o)
  112. {
  113. int threadIndex = (int)o;
  114. while (exception == null)
  115. {
  116. T entry;
  117. lock (enumerator)
  118. {
  119. if (!enumerator.MoveNext())
  120. break;
  121. entry = (T)enumerator.Current; // Explicit typecast for Mono's sake
  122. }
  123. try { body(entry); }
  124. catch (Exception ex) { exception = ex; break; }
  125. }
  126. if (Interlocked.Decrement(ref counter) == 0)
  127. threadFinishEvent.Set();
  128. }, i
  129. );
  130. }
  131. threadFinishEvent.WaitOne();
  132. threadFinishEvent.Close();
  133. if (exception != null)
  134. throw new Exception(exception.Message, exception);
  135. }
  136. /// <summary>
  137. /// Executes a series of tasks in parallel
  138. /// </summary>
  139. /// <param name="actions">A series of method bodies to execute</param>
  140. public static void Invoke(params Action[] actions)
  141. {
  142. Invoke(ProcessorCount, actions);
  143. }
  144. /// <summary>
  145. /// Executes a series of tasks in parallel
  146. /// </summary>
  147. /// <param name="threadCount">The number of concurrent execution threads to run</param>
  148. /// <param name="actions">A series of method bodies to execute</param>
  149. public static void Invoke(int threadCount, params Action[] actions)
  150. {
  151. int counter = threadCount;
  152. AutoResetEvent threadFinishEvent = new AutoResetEvent(false);
  153. int index = -1;
  154. Exception exception = null;
  155. for (int i = 0; i < threadCount; i++)
  156. {
  157. Util.FireAndForget(
  158. delegate(object o)
  159. {
  160. int threadIndex = (int)o;
  161. while (exception == null)
  162. {
  163. int currentIndex = Interlocked.Increment(ref index);
  164. if (currentIndex >= actions.Length)
  165. break;
  166. try { actions[currentIndex](); }
  167. catch (Exception ex) { exception = ex; break; }
  168. }
  169. if (Interlocked.Decrement(ref counter) == 0)
  170. threadFinishEvent.Set();
  171. }, i
  172. );
  173. }
  174. threadFinishEvent.WaitOne();
  175. threadFinishEvent.Close();
  176. if (exception != null)
  177. throw new Exception(exception.Message, exception);
  178. }
  179. }
  180. }