ThreadWorker.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. // ThreadWorker.cs
  2. //
  3. // Copyright (c) 2008 Jérémie "Garuma" Laval
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. //
  24. #if NET_4_0 || BOOTSTRAP_NET_4_0
  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 Action<Task> childWorkAdder;
  37. readonly EventWaitHandle waitHandle;
  38. readonly IProducerConsumerCollection<Task> sharedWorkQueue;
  39. // Flag to tell if workerThread is running
  40. int started = 0;
  41. readonly bool isLocal;
  42. readonly int workerLength;
  43. readonly int stealingStart;
  44. const int maxRetry = 5;
  45. const int sleepThreshold = 100;
  46. const int deepSleepTime = 10;
  47. Action threadInitializer;
  48. public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
  49. int maxStackSize, ThreadPriority priority, EventWaitHandle handle)
  50. : this (sched, others, sharedWorkQueue, true, maxStackSize, priority, handle)
  51. {
  52. }
  53. public ThreadWorker (IScheduler sched, ThreadWorker[] others, IProducerConsumerCollection<Task> sharedWorkQueue,
  54. bool createThread, int maxStackSize, ThreadPriority priority, EventWaitHandle handle)
  55. {
  56. this.others = others;
  57. this.dDeque = new CyclicDeque<Task> ();
  58. this.sharedWorkQueue = sharedWorkQueue;
  59. this.workerLength = others.Length;
  60. this.isLocal = !createThread;
  61. this.waitHandle = handle;
  62. this.childWorkAdder = delegate (Task t) {
  63. dDeque.PushBottom (t);
  64. sched.PulseAll ();
  65. };
  66. // Find the stealing start index randomly (then the traversal
  67. // will be done in Round-Robin fashion)
  68. do {
  69. this.stealingStart = r.Next(0, workerLength);
  70. } while (others[stealingStart] == this);
  71. InitializeUnderlyingThread (maxStackSize, priority);
  72. }
  73. void InitializeUnderlyingThread (int maxStackSize, ThreadPriority priority)
  74. {
  75. threadInitializer = delegate {
  76. // Special case of the participant ThreadWorker
  77. if (isLocal) {
  78. this.workerThread = Thread.CurrentThread;
  79. return;
  80. }
  81. this.workerThread = (maxStackSize == 0) ? new Thread (WorkerMethodWrapper) :
  82. new Thread (WorkerMethodWrapper, maxStackSize);
  83. this.workerThread.IsBackground = true;
  84. this.workerThread.Priority = priority;
  85. this.workerThread.Name = "ParallelFxThreadWorker";
  86. };
  87. threadInitializer ();
  88. }
  89. public void Dispose ()
  90. {
  91. Stop ();
  92. if (!isLocal && workerThread.ThreadState != ThreadState.Stopped)
  93. workerThread.Abort ();
  94. }
  95. public void Pulse ()
  96. {
  97. // If the thread was stopped then set it in use and restart it
  98. int result = Interlocked.Exchange (ref started, 1);
  99. if (result != 0)
  100. return;
  101. if (!isLocal) {
  102. if (this.workerThread.ThreadState != ThreadState.Unstarted) {
  103. threadInitializer ();
  104. }
  105. workerThread.Start ();
  106. }
  107. }
  108. public void Stop ()
  109. {
  110. // Set the flag to stop so that the while in the thread will stop
  111. // doing its infinite loop.
  112. started = 0;
  113. }
  114. // This is the actual method called in the Thread
  115. void WorkerMethodWrapper ()
  116. {
  117. int sleepTime = 0;
  118. SpinWait wait = new SpinWait ();
  119. // Main loop
  120. while (started == 1) {
  121. bool result = false;
  122. result = WorkerMethod ();
  123. if (result) {
  124. sleepTime = 0;
  125. wait = new SpinWait ();
  126. }
  127. // Wait a little and if the Thread has been more sleeping than working shut it down
  128. wait.SpinOnce ();
  129. // If we are spinning too much, have a deeper sleep
  130. if (sleepTime++ > sleepThreshold)
  131. while (!waitHandle.WaitOne (deepSleepTime) && sharedWorkQueue.Count == 0);
  132. }
  133. started = 0;
  134. }
  135. // Main method, used to do all the logic of retrieving, processing and stealing work.
  136. bool WorkerMethod ()
  137. {
  138. bool result = false;
  139. bool hasStolenFromOther;
  140. do {
  141. hasStolenFromOther = false;
  142. Task value;
  143. // We fill up our work deque concurrently with other ThreadWorker
  144. while (sharedWorkQueue.Count > 0) {
  145. while (sharedWorkQueue.TryTake (out value)) {
  146. dDeque.PushBottom (value);
  147. }
  148. // Now we process our work
  149. while (dDeque.PopBottom (out value) == PopResult.Succeed) {
  150. if (value != null) {
  151. value.Execute (childWorkAdder);
  152. result = true;
  153. }
  154. }
  155. }
  156. // When we have finished, steal from other worker
  157. ThreadWorker other;
  158. // Repeat the operation a little so that we can let other things process.
  159. for (int j = 0; j < maxRetry; j++) {
  160. // Start stealing with the ThreadWorker at our right to minimize contention
  161. for (int it = stealingStart; it < stealingStart + workerLength; it++) {
  162. int i = it % workerLength;
  163. if ((other = others [i]) == null || other == this)
  164. continue;
  165. // Maybe make this steal more than one item at a time, see TODO.
  166. if (other.dDeque.PopTop (out value) == PopResult.Succeed) {
  167. hasStolenFromOther = true;
  168. if (value != null) {
  169. value.Execute (childWorkAdder);
  170. result = true;
  171. }
  172. }
  173. }
  174. }
  175. } while (sharedWorkQueue.Count > 0 || hasStolenFromOther);
  176. return result;
  177. }
  178. // Almost same as above but with an added predicate and treating one item at a time.
  179. // It's used by Scheduler Participate(...) method for special waiting case like
  180. // Task.WaitAll(someTasks) or Task.WaitAny(someTasks)
  181. // Predicate should be really fast and not blocking as it is called a good deal of time
  182. // Also, the method skip tasks that are LongRunning to avoid blocking (Task are not LongRunning by default)
  183. public static void WorkerMethod (Func<bool> predicate, IProducerConsumerCollection<Task> sharedWorkQueue,
  184. ThreadWorker[] others)
  185. {
  186. SpinWait wait = new SpinWait ();
  187. while (!predicate ()) {
  188. Task value;
  189. // Dequeue only one item as we have restriction
  190. if (sharedWorkQueue.TryTake (out value)) {
  191. if (value != null) {
  192. if (CheckTaskFitness (value))
  193. value.Execute (null);
  194. else
  195. sharedWorkQueue.TryAdd (value);
  196. }
  197. }
  198. // First check to see if we comply to predicate
  199. if (predicate ())
  200. return;
  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. if (CheckTaskFitness (value))
  209. value.Execute (null);
  210. else
  211. sharedWorkQueue.TryAdd (value);
  212. }
  213. }
  214. if (predicate ())
  215. return;
  216. }
  217. wait.SpinOnce ();
  218. }
  219. }
  220. static bool CheckTaskFitness (Task t)
  221. {
  222. return (t.CreationOptions | TaskCreationOptions.LongRunning) > 0;
  223. }
  224. public bool Finished {
  225. get {
  226. return started == 0;
  227. }
  228. }
  229. public bool IsLocal {
  230. get {
  231. return isLocal;
  232. }
  233. }
  234. public int Id {
  235. get {
  236. return workerThread.ManagedThreadId;
  237. }
  238. }
  239. public bool Equals (ThreadWorker other)
  240. {
  241. return (other == null) ? false : object.ReferenceEquals (this.dDeque, other.dDeque);
  242. }
  243. public override bool Equals (object obj)
  244. {
  245. ThreadWorker temp = obj as ThreadWorker;
  246. return temp == null ? false : Equals (temp);
  247. }
  248. public override int GetHashCode ()
  249. {
  250. return workerThread.ManagedThreadId.GetHashCode ();
  251. }
  252. }
  253. }
  254. #endif