ThreadPool.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. //
  2. // System.Threading.ThreadPool
  3. //
  4. // Author:
  5. // Patrik Torstensson
  6. // Dick Porter ([email protected])
  7. //
  8. // (C) Ximian, Inc. http://www.ximian.com
  9. // (C) Patrik Torstensson
  10. //
  11. using System;
  12. using System.Collections;
  13. namespace System.Threading {
  14. /// <summary> (Patrik T notes)
  15. /// This threadpool is focused on saving resources not giving max performance.
  16. ///
  17. /// Note, this class is not perfect but it works. ;-) Should also replace
  18. /// the queue with an internal one (performance)
  19. ///
  20. /// This class should also use a specialized queue to increase performance..
  21. /// </summary>
  22. ///
  23. public sealed class ThreadPool {
  24. internal struct ThreadPoolWorkItem {
  25. public WaitCallback _CallBack;
  26. public object _Context;
  27. }
  28. private int _ThreadTimeout;
  29. private long _MaxThreads;
  30. private long _CurrentThreads;
  31. private long _ThreadsInUse;
  32. private long _RequestInQueue;
  33. private long _ThreadCreateTriggerRequests;
  34. private Thread _MonitorThread;
  35. private Queue _RequestQueue;
  36. private ArrayList _Threads;
  37. private ManualResetEvent _DataInQueue;
  38. static ThreadPool _Threadpool;
  39. static ThreadPool() {
  40. _Threadpool = new ThreadPool();
  41. }
  42. private ThreadPool() {
  43. // 30 sec timeout default
  44. _ThreadTimeout = 30 * 1000;
  45. // Used to signal that there is data in the queue
  46. _DataInQueue = new ManualResetEvent(false);
  47. _Threads = ArrayList.Synchronized(new ArrayList());
  48. // Holds requests..
  49. _RequestQueue = Queue.Synchronized(new Queue(128));
  50. // TODO: This should be 2 x number of CPU:s in the box
  51. _MaxThreads = 16;
  52. _CurrentThreads = 0;
  53. _RequestInQueue = 0;
  54. _ThreadsInUse = 0;
  55. _ThreadCreateTriggerRequests = 5;
  56. // TODO: This temp starts one thread, remove this..
  57. CheckIfStartThread();
  58. // Keeps track of requests in the queue and increases the number of threads if needed
  59. // PT: Disabled - causes problems during shutdown
  60. //_MonitorThread = new Thread(new ThreadStart(MonitorThread));
  61. //_MonitorThread.Start();
  62. }
  63. internal void RemoveThread() {
  64. Interlocked.Decrement(ref _CurrentThreads);
  65. _Threads.Remove(Thread.CurrentThread);
  66. }
  67. internal void CheckIfStartThread() {
  68. bool bCreateThread = false;
  69. if (_CurrentThreads == 0) {
  70. bCreateThread = true;
  71. }
  72. if (( _MaxThreads == -1 || _CurrentThreads < _MaxThreads) &&
  73. _ThreadsInUse > 0 &&
  74. _RequestInQueue >= _ThreadCreateTriggerRequests) {
  75. bCreateThread = true;
  76. }
  77. if (bCreateThread) {
  78. Interlocked.Increment(ref _CurrentThreads);
  79. Thread Start = new Thread(new ThreadStart(WorkerThread));
  80. Start.IsThreadPoolThreadInternal = true;
  81. Start.IsBackground = true;
  82. Start.Start();
  83. _Threads.Add(Start);
  84. }
  85. }
  86. internal void AddItem(ref ThreadPoolWorkItem Item) {
  87. if (Interlocked.Increment(ref _RequestInQueue) == 1) {
  88. _DataInQueue.Set();
  89. }
  90. _RequestQueue.Enqueue(Item);
  91. }
  92. // Work Thread main function
  93. internal void WorkerThread() {
  94. bool bWaitForData = true;
  95. while (true) {
  96. if (bWaitForData) {
  97. if (!_DataInQueue.WaitOne(_ThreadTimeout, false)) {
  98. // Keep one thread running
  99. if (_CurrentThreads > 1) {
  100. // timeout
  101. RemoveThread();
  102. return;
  103. }
  104. }
  105. }
  106. Interlocked.Increment(ref _ThreadsInUse);
  107. // TODO: Remove when we know how to stop the watch thread
  108. CheckIfStartThread();
  109. try {
  110. ThreadPoolWorkItem oItem = (ThreadPoolWorkItem) _RequestQueue.Dequeue();
  111. if (Interlocked.Decrement(ref _RequestInQueue) == 0) {
  112. _DataInQueue.Reset();
  113. }
  114. oItem._CallBack(oItem._Context);
  115. }
  116. catch (InvalidOperationException) {
  117. // Queue empty
  118. bWaitForData = true;
  119. }
  120. catch (ThreadAbortException) {
  121. // We will leave here.. (thread abort can't be handled)
  122. RemoveThread();
  123. }
  124. finally {
  125. Interlocked.Decrement(ref _ThreadsInUse);
  126. }
  127. }
  128. }
  129. /* This is currently not in use
  130. internal void MonitorThread() {
  131. while (true) {
  132. if (_DataInQueue.WaitOne ()) {
  133. CheckIfStartThread();
  134. }
  135. Thread.Sleep(500);
  136. }
  137. }
  138. */
  139. internal bool QueueUserWorkItemInternal(WaitCallback callback) {
  140. return QueueUserWorkItem(callback, null);
  141. }
  142. internal bool QueueUserWorkItemInternal(WaitCallback callback, object context) {
  143. ThreadPoolWorkItem Item = new ThreadPoolWorkItem();
  144. Item._CallBack = callback;
  145. Item._Context = context;
  146. AddItem(ref Item);
  147. // LAMESPEC: Return value? should use exception here if anything goes wrong
  148. return true;
  149. }
  150. public static bool BindHandle(IntPtr osHandle) {
  151. throw new NotSupportedException("This is a win32 specific method, not supported Mono");
  152. }
  153. public static bool QueueUserWorkItem(WaitCallback callback) {
  154. return _Threadpool.QueueUserWorkItemInternal(callback);
  155. }
  156. public static bool QueueUserWorkItem(WaitCallback callback, object state) {
  157. return _Threadpool.QueueUserWorkItemInternal(callback, state);
  158. }
  159. public static bool UnsafeQueueUserWorkItem(WaitCallback callback, object state) {
  160. return _Threadpool.QueueUserWorkItemInternal(callback, state);
  161. }
  162. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) {
  163. if (millisecondsTimeOutInterval < -1) {
  164. throw new ArgumentOutOfRangeException("timeout < -1");
  165. }
  166. return RegisterWaitForSingleObject (waitObject, callback, state, TimeSpan.FromMilliseconds (Convert.ToDouble(millisecondsTimeOutInterval)), executeOnlyOnce);
  167. }
  168. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) {
  169. if (millisecondsTimeOutInterval < -1) {
  170. throw new ArgumentOutOfRangeException("timeout < -1");
  171. }
  172. return RegisterWaitForSingleObject (waitObject, callback, state, TimeSpan.FromMilliseconds (Convert.ToDouble(millisecondsTimeOutInterval)), executeOnlyOnce);
  173. }
  174. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce) {
  175. // LAMESPEC: I assume it means "timeout" when it says "millisecondsTimeOutInterval"
  176. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  177. if (ms < -1) {
  178. throw new ArgumentOutOfRangeException("timeout < -1");
  179. }
  180. if (ms > Int32.MaxValue) {
  181. throw new NotSupportedException("timeout too large");
  182. }
  183. RegisteredWaitHandle waiter = new RegisteredWaitHandle (waitObject, callback, state, timeout, executeOnlyOnce);
  184. _Threadpool.QueueUserWorkItemInternal (new WaitCallback(waiter.Wait), null);
  185. return waiter;
  186. }
  187. [CLSCompliant(false)]
  188. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) {
  189. return RegisterWaitForSingleObject (waitObject, callback, state, TimeSpan.FromMilliseconds (Convert.ToDouble(millisecondsTimeOutInterval)), executeOnlyOnce);
  190. }
  191. [MonoTODO]
  192. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) {
  193. throw new NotImplementedException();
  194. }
  195. [MonoTODO]
  196. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) {
  197. throw new NotImplementedException();
  198. }
  199. [MonoTODO]
  200. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce) {
  201. throw new NotImplementedException();
  202. }
  203. [CLSCompliant(false)][MonoTODO]
  204. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) {
  205. throw new NotImplementedException();
  206. }
  207. }
  208. }