ThreadWorker.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. this.dDeque = new CyclicDeque<Task> ();
  59. this.sharedWorkQueue = sharedWorkQueue;
  60. this.workerLength = others.Length;
  61. this.isLocal = !createThread;
  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. };
  86. threadInitializer ();
  87. }
  88. public void Dispose ()
  89. {
  90. Stop ();
  91. if (!isLocal && workerThread.ThreadState != ThreadState.Stopped)
  92. workerThread.Abort ();
  93. }
  94. public void Pulse ()
  95. {
  96. // If the thread was stopped then set it in use and restart it
  97. int result = Interlocked.Exchange (ref started, 1);
  98. if (result != 0)
  99. return;
  100. if (!isLocal) {
  101. if (this.workerThread.ThreadState != ThreadState.Unstarted) {
  102. threadInitializer ();
  103. }
  104. workerThread.Start ();
  105. }
  106. }
  107. public void Stop ()
  108. {
  109. // Set the flag to stop so that the while in the thread will stop
  110. // doing its infinite loop.
  111. started = 0;
  112. }
  113. // This is the actual method called in the Thread
  114. void WorkerMethodWrapper ()
  115. {
  116. int sleepTime = 0;
  117. // Main loop
  118. while (started == 1) {
  119. bool result = false;
  120. try {
  121. result = WorkerMethod ();
  122. } catch (Exception e) {
  123. Console.WriteLine (e.ToString ());
  124. }
  125. // Wait a little and if the Thread has been more sleeping than working shut it down
  126. wait.SpinOnce ();
  127. if (result)
  128. sleepTime = 0;
  129. if (sleepTime++ > sleepThreshold)
  130. break;
  131. }
  132. started = 0;
  133. }
  134. // Main method, used to do all the logic of retrieving, processing and stealing work.
  135. bool WorkerMethod ()
  136. {
  137. bool result = false;
  138. bool hasStolenFromOther;
  139. do {
  140. hasStolenFromOther = false;
  141. Task value;
  142. // We fill up our work deque concurrently with other ThreadWorker
  143. while (sharedWorkQueue.Count > 0) {
  144. while (sharedWorkQueue.TryTake (out value)) {
  145. dDeque.PushBottom (value);
  146. }
  147. // Now we process our work
  148. while (dDeque.PopBottom (out value) == PopResult.Succeed) {
  149. if (value != null) {
  150. value.Execute (childWorkAdder);
  151. result = true;
  152. }
  153. }
  154. }
  155. // When we have finished, steal from other worker
  156. ThreadWorker other;
  157. // Repeat the operation a little so that we can let other things process.
  158. for (int j = 0; j < maxRetry; j++) {
  159. // Start stealing with the ThreadWorker at our right to minimize contention
  160. for (int it = stealingStart; it < stealingStart + workerLength; it++) {
  161. int i = it % workerLength;
  162. if ((other = others [i]) == null || other == this)
  163. continue;
  164. // Maybe make this steal more than one item at a time, see TODO.
  165. if (other.dDeque.PopTop (out value) == PopResult.Succeed) {
  166. hasStolenFromOther = true;
  167. if (value != null) {
  168. value.Execute (childWorkAdder);
  169. result = true;
  170. }
  171. }
  172. }
  173. }
  174. } while (sharedWorkQueue.Count > 0 || hasStolenFromOther);
  175. return result;
  176. }
  177. // Almost same as above but with an added predicate and treating one item at a time.
  178. // It's used by Scheduler Participate(...) method for special waiting case like
  179. // Task.WaitAll(someTasks) or Task.WaitAny(someTasks)
  180. // Predicate should be really fast and not blocking as it is called a good deal of time
  181. // Also, the method skip tasks that are LongRunning to avoid blocking (Task are not LongRunning by default)
  182. public static void WorkerMethod (Func<bool> predicate, IProducerConsumerCollection<Task> sharedWorkQueue,
  183. ThreadWorker[] others)
  184. {
  185. while (!predicate ()) {
  186. Task value;
  187. // Dequeue only one item as we have restriction
  188. if (sharedWorkQueue.TryTake (out value)) {
  189. if (value != null) {
  190. if (CheckTaskFitness (value))
  191. value.Execute (null);
  192. else
  193. sharedWorkQueue.TryAdd (value);
  194. }
  195. }
  196. // First check to see if we comply to predicate
  197. if (predicate ()) {
  198. return;
  199. }
  200. // Try to complete other work by stealing since our desired tasks may be in other worker
  201. ThreadWorker other;
  202. for (int i = 0; i < others.Length; i++) {
  203. if ((other = others [i]) == null)
  204. continue;
  205. if (other.dDeque.PopTop (out value) == PopResult.Succeed) {
  206. if (value != null) {
  207. if (CheckTaskFitness (value))
  208. value.Execute (null);
  209. else
  210. sharedWorkQueue.TryAdd (value);
  211. }
  212. }
  213. if (predicate ()) {
  214. return;
  215. }
  216. }
  217. }
  218. }
  219. static bool CheckTaskFitness (Task t)
  220. {
  221. return (t.CreationOptions | TaskCreationOptions.LongRunning) > 0;
  222. }
  223. public bool Finished {
  224. get {
  225. return started == 0;
  226. }
  227. }
  228. public bool IsLocal {
  229. get {
  230. return isLocal;
  231. }
  232. }
  233. public int Id {
  234. get {
  235. return workerThread.ManagedThreadId;
  236. }
  237. }
  238. public bool Equals (ThreadWorker other)
  239. {
  240. return (other == null) ? false : object.ReferenceEquals (this.dDeque, other.dDeque);
  241. }
  242. public override bool Equals (object obj)
  243. {
  244. ThreadWorker temp = obj as ThreadWorker;
  245. return temp == null ? false : Equals (temp);
  246. }
  247. public override int GetHashCode ()
  248. {
  249. return workerThread.ManagedThreadId.GetHashCode ();
  250. }
  251. }
  252. }
  253. #endif