OrderingEnumerator.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. //
  2. // OrderingEnumerator.cs
  3. //
  4. // Author:
  5. // Jérémie "Garuma" Laval <[email protected]>
  6. //
  7. // Copyright (c) 2010 Jérémie "Garuma" Laval
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if NET_4_0
  27. using System;
  28. using System.Threading;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Collections.Concurrent;
  32. namespace System.Linq.Parallel
  33. {
  34. internal class OrderingEnumerator<T> : IEnumerator<T>
  35. {
  36. internal class SlotBucket
  37. {
  38. readonly ConcurrentDictionary<long, T> temporaryArea = new ConcurrentDictionary<long, T> ();
  39. readonly KeyValuePair<long, T>[] stagingArea;
  40. long currentIndex;
  41. readonly int count;
  42. CountdownEvent stagingCount;
  43. CountdownEvent participantCount;
  44. CancellationTokenSource src = new CancellationTokenSource ();
  45. CancellationToken mergedToken;
  46. public SlotBucket (int count, CancellationToken token)
  47. {
  48. this.count = count;
  49. stagingCount = new CountdownEvent (count);
  50. participantCount = new CountdownEvent (count);
  51. stagingArea = new KeyValuePair<long, T>[count];
  52. currentIndex = -count;
  53. mergedToken = CancellationTokenSource.CreateLinkedTokenSource (src.Token, token).Token;
  54. }
  55. public void Add (KeyValuePair<long, T> value)
  56. {
  57. long index = value.Key;
  58. if (index >= currentIndex && index < currentIndex + count) {
  59. stagingArea[index % count] = value;
  60. stagingCount.Signal ();
  61. } else {
  62. temporaryArea.TryAdd (index, value.Value);
  63. if (index >= currentIndex && index < currentIndex + count) {
  64. T dummy;
  65. if (temporaryArea.TryRemove (index, out dummy)) {
  66. stagingArea[index % count] = value;
  67. stagingCount.Signal ();
  68. }
  69. }
  70. }
  71. }
  72. // Called by each worker's endAction
  73. public void EndParticipation ()
  74. {
  75. if (participantCount.Signal ())
  76. src.Cancel ();
  77. }
  78. // Called at the end with ContinueAll
  79. public void Stop ()
  80. {
  81. src.Cancel ();
  82. }
  83. bool Skim ()
  84. {
  85. bool result = false;
  86. for (int i = 0; i < count; i++) {
  87. T temp;
  88. int index = i + (int)currentIndex;
  89. if (stagingArea[i].Key != -1)
  90. continue;
  91. if (!temporaryArea.TryRemove (index, out temp))
  92. continue;
  93. result = true;
  94. stagingArea [i] = new KeyValuePair<long, T> (index, temp);
  95. if (stagingCount.Signal ())
  96. break;
  97. }
  98. return result;
  99. }
  100. void Clean ()
  101. {
  102. for (int i = 0; i < stagingArea.Length; i++)
  103. stagingArea[i] = new KeyValuePair<long, T> (-1, default (T));
  104. }
  105. public KeyValuePair<long, T>[] Wait ()
  106. {
  107. Clean ();
  108. stagingCount.Reset ();
  109. Interlocked.Add (ref currentIndex, count);
  110. Skim ();
  111. while (!stagingCount.IsSet) {
  112. if (!participantCount.IsSet)
  113. try {
  114. stagingCount.Wait (mergedToken);
  115. } catch {
  116. Skim ();
  117. }
  118. // Ok so basically we hit the case where we return null but there is actually
  119. // every remaining element inside temporaryArea. Thing is that index are basically getting messed up (probably)
  120. // So Skim doesn't see them and inaccurately say there is nothing remaining.
  121. // To prove this, adding a if (temporaryArea.IsEmpty) before returning null result in infinite loop
  122. // plus if it was a problem with something here it would show elsewhere so the problem definitely comes from
  123. // SelectMany.
  124. if (participantCount.IsSet) {
  125. if (Skim ())
  126. continue;
  127. // Totally finished
  128. if (stagingArea.Any (s => s.Key != -1))
  129. break;
  130. else
  131. return null;
  132. }
  133. }
  134. return stagingArea;
  135. }
  136. }
  137. SlotBucket slotBucket;
  138. KeyValuePair<long, T>[] slot;
  139. int current;
  140. internal OrderingEnumerator (int num, CancellationToken token)
  141. {
  142. slotBucket = new SlotBucket (num, token);
  143. }
  144. public void Dispose ()
  145. {
  146. slotBucket.Stop ();
  147. }
  148. public void Reset ()
  149. {
  150. }
  151. public bool MoveNext ()
  152. {
  153. do {
  154. if (slot == null || ++current >= slot.Length) {
  155. if ((slot = slotBucket.Wait ()) == null)
  156. return false;
  157. current = 0;
  158. }
  159. } while (slot[current].Key == -1);
  160. return true;
  161. }
  162. public T Current {
  163. get {
  164. return slot[current].Value;
  165. }
  166. }
  167. object IEnumerator.Current {
  168. get {
  169. return slot[current].Value;
  170. }
  171. }
  172. public void Add (KeyValuePair<long, T> value, CancellationToken token)
  173. {
  174. slotBucket.Add (value);
  175. }
  176. // Called by each worker's endAction
  177. public void EndParticipation ()
  178. {
  179. slotBucket.EndParticipation ();
  180. }
  181. // Called at the end with ContinueAll
  182. public void Stop ()
  183. {
  184. slotBucket.Stop ();
  185. }
  186. }
  187. }
  188. #endif