ThreadWorker.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #if NET_4_0
  2. // ThreadWorker.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.Threading;
  27. using System.Collections.Concurrent;
  28. namespace System.Threading.Tasks
  29. {
  30. internal class ThreadWorker: IDisposable
  31. {
  32. static Random r = new Random ();
  33. Thread workerThread;
  34. readonly ThreadWorker[] others;
  35. internal readonly IDequeOperations<Task> dDeque;
  36. readonly IProducerConsumerCollection<Task> sharedWorkQueue;
  37. readonly Action<Task> childWorkAdder;
  38. // Flag to tell if workerThread is running
  39. int started = 0;
  40. readonly bool isLocal;
  41. readonly int workerLength;
  42. readonly int stealingStart;
  43. const int maxRetry = 5;
  44. #region Sleep related fields
  45. readonly SpinWait wait = new SpinWait ();
  46. const int sleepThreshold = 100000;
  47. #endregion
  48. Action threadInitializer;
  49. public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
  50. int maxStackSize, ThreadPriority priority)
  51. : this (sched, others, sharedWorkQueue, true, maxStackSize, priority)
  52. {
  53. }
  54. public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
  55. bool createThread, int maxStackSize, ThreadPriority priority)
  56. {
  57. this.others = others;
  58. // if (!string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("USE_CYCLIC"))) {
  59. // Console.WriteLine ("Using cyclic deque");
  60. // this.dDeque = new CyclicDeque<Task> ();
  61. // } else {
  62. // this.dDeque = new DynamicDeque<Task> ();
  63. // }
  64. this.dDeque = new CyclicDeque<Task> ();
  65. this.sharedWorkQueue = sharedWorkQueue;
  66. this.workerLength = others.Length;
  67. this.isLocal = !createThread;
  68. this.childWorkAdder = delegate (Task t) {
  69. dDeque.PushBottom (t);
  70. sched.PulseAll ();
  71. };
  72. // Find the stealing start index randomly (then the traversal
  73. // will be done in Round-Robin fashion)
  74. do {
  75. this.stealingStart = r.Next(0, workerLength);
  76. } while (others[stealingStart] == this);
  77. InitializeUnderlyingThread (maxStackSize, priority);
  78. }
  79. void InitializeUnderlyingThread (int maxStackSize, ThreadPriority priority)
  80. {
  81. threadInitializer = delegate {
  82. // Special case of the participant ThreadWorker
  83. if (isLocal) {
  84. this.workerThread = Thread.CurrentThread;
  85. return;
  86. }
  87. this.workerThread = (maxStackSize == 0) ? new Thread (WorkerMethodWrapper) :
  88. new Thread (WorkerMethodWrapper, maxStackSize);
  89. this.workerThread.IsBackground = true;
  90. this.workerThread.Priority = priority;
  91. };
  92. threadInitializer ();
  93. }
  94. public void Dispose ()
  95. {
  96. Stop ();
  97. if (!isLocal && workerThread.ThreadState != ThreadState.Stopped)
  98. workerThread.Abort ();
  99. }
  100. public void Pulse ()
  101. {
  102. // If the thread was stopped then set it in use and restart it
  103. int result = Interlocked.Exchange (ref started, 1);
  104. if (result != 0)
  105. return;
  106. if (!isLocal) {
  107. if (this.workerThread.ThreadState != ThreadState.Unstarted) {
  108. threadInitializer ();
  109. }
  110. workerThread.Start ();
  111. }
  112. }
  113. public void Stop ()
  114. {
  115. // Set the flag to stop so that the while in the thread will stop
  116. // doing its infinite loop.
  117. started = 0;
  118. }
  119. // This is the actual method called in the Thread
  120. void WorkerMethodWrapper ()
  121. {
  122. int sleepTime = 0;
  123. // Main loop
  124. while (started == 1) {
  125. bool result = false;
  126. try {
  127. result = WorkerMethod ();
  128. } catch (Exception e) {
  129. Console.WriteLine (e.ToString ());
  130. }
  131. // Wait a little and if the Thread has been more sleeping than working shut it down
  132. wait.SpinOnce ();
  133. if (result)
  134. sleepTime = 0;
  135. if (sleepTime++ > sleepThreshold)
  136. break;
  137. }
  138. started = 0;
  139. }
  140. // Main method, used to do all the logic of retrieving, processing and stealing work.
  141. bool WorkerMethod ()
  142. {
  143. bool result = false;
  144. bool hasStolenFromOther;
  145. do {
  146. hasStolenFromOther = false;
  147. Task value;
  148. // We fill up our work deque concurrently with other ThreadWorker
  149. while (sharedWorkQueue.Count > 0) {
  150. while (sharedWorkQueue.TryTake (out value)) {
  151. dDeque.PushBottom (value);
  152. }
  153. // Now we process our work
  154. while (dDeque.PopBottom (out value) == PopResult.Succeed) {
  155. if (value != null) {
  156. value.Execute (childWorkAdder);
  157. result = true;
  158. }
  159. }
  160. }
  161. // When we have finished, steal from other worker
  162. ThreadWorker other;
  163. // Repeat the operation a little so that we can let other things process.
  164. for (int j = 0; j < maxRetry; j++) {
  165. // Start stealing with the ThreadWorker at our right to minimize contention
  166. for (int it = stealingStart; it < stealingStart + workerLength; it++) {
  167. int i = it % workerLength;
  168. if ((other = others [i]) == null || other == this)
  169. continue;
  170. // Maybe make this steal more than one item at a time, see TODO.
  171. if (other.dDeque.PopTop (out value) == PopResult.Succeed) {
  172. hasStolenFromOther = true;
  173. if (value != null) {
  174. value.Execute (childWorkAdder);
  175. result = true;
  176. }
  177. }
  178. }
  179. }
  180. } while (sharedWorkQueue.Count > 0 || hasStolenFromOther);
  181. return result;
  182. }
  183. // Almost same as above but with an added predicate and treating one item at a time.
  184. // It's used by Scheduler Participate(...) method for special waiting case like
  185. // Task.WaitAll(someTasks) or Task.WaitAny(someTasks)
  186. public static void WorkerMethod (Func<bool> predicate, IProducerConsumerCollection<Task> sharedWorkQueue,
  187. ThreadWorker[] others)
  188. {
  189. while (!predicate ()) {
  190. Task value;
  191. // Dequeue only one item as we have restriction
  192. if (sharedWorkQueue.TryTake (out value)) {
  193. if (value != null) {
  194. value.Execute (null);
  195. }
  196. }
  197. // First check to see if we comply to predicate
  198. if (predicate ()) {
  199. return;
  200. }
  201. // Try to complete other work by stealing since our desired tasks may be in other worker
  202. ThreadWorker other;
  203. for (int i = 0; i < others.Length; i++) {
  204. if ((other = others [i]) == null)
  205. continue;
  206. if (other.dDeque.PopTop (out value) == PopResult.Succeed) {
  207. if (value != null) {
  208. value.Execute (null);
  209. }
  210. }
  211. if (predicate ()) {
  212. return;
  213. }
  214. }
  215. }
  216. }
  217. public bool Finished {
  218. get {
  219. return started == 0;
  220. }
  221. }
  222. public bool IsLocal {
  223. get {
  224. return isLocal;
  225. }
  226. }
  227. public int Id {
  228. get {
  229. return workerThread.ManagedThreadId;
  230. }
  231. }
  232. public bool Equals (ThreadWorker other)
  233. {
  234. return (other == null) ? false : object.ReferenceEquals (this.dDeque, other.dDeque);
  235. }
  236. public override bool Equals (object obj)
  237. {
  238. ThreadWorker temp = obj as ThreadWorker;
  239. return temp == null ? false : Equals (temp);
  240. }
  241. public override int GetHashCode ()
  242. {
  243. return workerThread.ManagedThreadId.GetHashCode ();
  244. }
  245. }
  246. }
  247. #endif