Parallel.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. object syncRoot = new object();
  108. Exception exception = null;
  109. for (int i = 0; i < threadCount; i++)
  110. {
  111. Util.FireAndForget(
  112. delegate(object o)
  113. {
  114. // int threadIndex = (int)o;
  115. while (exception == null)
  116. {
  117. T entry;
  118. lock (syncRoot)
  119. {
  120. if (!enumerator.MoveNext())
  121. break;
  122. entry = (T)enumerator.Current; // Explicit typecast for Mono's sake
  123. }
  124. try { body(entry); }
  125. catch (Exception ex) { exception = ex; break; }
  126. }
  127. if (Interlocked.Decrement(ref counter) == 0)
  128. threadFinishEvent.Set();
  129. }, i
  130. );
  131. }
  132. threadFinishEvent.WaitOne();
  133. threadFinishEvent.Close();
  134. if (exception != null)
  135. throw new Exception(exception.Message, exception);
  136. }
  137. /// <summary>
  138. /// Executes a series of tasks in parallel
  139. /// </summary>
  140. /// <param name="actions">A series of method bodies to execute</param>
  141. public static void Invoke(params Action[] actions)
  142. {
  143. Invoke(ProcessorCount, actions);
  144. }
  145. /// <summary>
  146. /// Executes a series of tasks in parallel
  147. /// </summary>
  148. /// <param name="threadCount">The number of concurrent execution threads to run</param>
  149. /// <param name="actions">A series of method bodies to execute</param>
  150. public static void Invoke(int threadCount, params Action[] actions)
  151. {
  152. int counter = threadCount;
  153. AutoResetEvent threadFinishEvent = new AutoResetEvent(false);
  154. int index = -1;
  155. Exception exception = null;
  156. for (int i = 0; i < threadCount; i++)
  157. {
  158. Util.FireAndForget(
  159. delegate(object o)
  160. {
  161. // int threadIndex = (int)o;
  162. while (exception == null)
  163. {
  164. int currentIndex = Interlocked.Increment(ref index);
  165. if (currentIndex >= actions.Length)
  166. break;
  167. try { actions[currentIndex](); }
  168. catch (Exception ex) { exception = ex; break; }
  169. }
  170. if (Interlocked.Decrement(ref counter) == 0)
  171. threadFinishEvent.Set();
  172. }, i
  173. );
  174. }
  175. threadFinishEvent.WaitOne();
  176. threadFinishEvent.Close();
  177. if (exception != null)
  178. throw new Exception(exception.Message, exception);
  179. }
  180. }
  181. }