Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ThreadPool.cs « System.Threading « corlib « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: af79eac307be91fe94c698659624219b04a22162 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//
// System.Threading.ThreadPool
//
// Author:
//   Patrik Torstensson (patrik.torstensson@labs2.com)
//   Dick Porter (dick@ximian.com)
//
// (C) Ximian, Inc.  http://www.ximian.com
// (C) Patrik Torstensson
//
using System;
using System.Collections;

namespace System.Threading
{
   /// <summary> (Patrik T notes)
   /// This threadpool is focused on saving resources not giving max performance. 
   /// 
   /// Note, this class is not perfect but it works. ;-) Should also replace
   /// the queue with an internal one (performance)
   /// 
   /// This class should also use a specialized queue to increase performance..
   /// </summary
   /// 
   public sealed class ThreadPool {
      internal struct ThreadPoolWorkItem {
         public WaitCallback _CallBack;
         public object _Context;
      }

      private int _ThreadTimeout;

      private long _MaxThreads;
      private long _CurrentThreads;
      private long _ThreadsInUse;
      private long _RequestInQueue;
      private long _ThreadCreateTriggerRequests;

      private Thread _MonitorThread;
      private Queue _RequestQueue;

      private ArrayList _Threads;
      private ManualResetEvent _DataInQueue; 

      static ThreadPool _Threadpool;

      static ThreadPool() {
         _Threadpool = new ThreadPool();
      }

      private ThreadPool() {
         // 30 sec timeout default
         _ThreadTimeout = 30 * 1000; 

         // Used to signal that there is data in the queue
         _DataInQueue = new ManualResetEvent(false);
         
         _Threads = ArrayList.Synchronized(new ArrayList());

         // Holds requests..
         _RequestQueue = Queue.Synchronized(new Queue(128));

         _MaxThreads = 64;
         _CurrentThreads = 0;
         _RequestInQueue = 0;
         _ThreadsInUse = 0;
         _ThreadCreateTriggerRequests = 5;

         // Keeps track of requests in the queue and inreases the number of threads if neededs
         _MonitorThread = new Thread(new ThreadStart(MonitorThread));
         _MonitorThread.Start();
      }

      internal void RemoveThread() {
         Interlocked.Decrement(ref _CurrentThreads);
         _Threads.Remove(Thread.CurrentThread);
      }

      internal void CheckIfStartThread() {
         bool bCreateThread = false;

         if (_CurrentThreads == 0) {
            bCreateThread = true;
         }

         if ((_MaxThreads == -1 || _CurrentThreads < _MaxThreads) && _ThreadsInUse > 0 && _RequestInQueue > _ThreadCreateTriggerRequests) {
            bCreateThread = true;
         }

         if (bCreateThread) {
            Interlocked.Increment(ref _CurrentThreads);
      
            Thread Start = new Thread(new ThreadStart(WorkerThread));
            Start.Start();
            Start.IsThreadPoolThreadInternal = true;
            
            _Threads.Add(Start);
         }
      }

      internal void AddItem(ref ThreadPoolWorkItem Item) {
         CheckIfStartThread();
         
         if (Interlocked.Increment(ref _RequestInQueue) == 1) {
            _DataInQueue.Set();
         }

         _RequestQueue.Enqueue(Item);
      }

      // Work Thread main function
      internal void WorkerThread() {
         bool bWaitForData = true;

         while (true) {
            if (bWaitForData) {
               if (!_DataInQueue.WaitOne(_ThreadTimeout, false)) {
                  // timeout
                  RemoveThread();
                  return;
               }
            }

            Interlocked.Increment(ref _ThreadsInUse);

            try {
               ThreadPoolWorkItem oItem = (ThreadPoolWorkItem) _RequestQueue.Dequeue();

               if (Interlocked.Decrement(ref _RequestInQueue) == 0) {
                  _DataInQueue.Reset();
               }

               oItem._CallBack(oItem._Context);
            }
            catch (InvalidOperationException) {
               // Queue empty
               bWaitForData = true;
            }
            catch (ThreadAbortException) {
               // We will leave here.. (thread abort can't be handled)
               RemoveThread();
            }
            finally {
               Interlocked.Decrement(ref _ThreadsInUse);
            }
         }
      }

      internal void MonitorThread() {
         while (true) {
            Thread.Sleep(500);

            CheckIfStartThread();
         }
      }

      internal bool QueueUserWorkItemInternal(WaitCallback callback) {
         return QueueUserWorkItem(callback, null);
      }

      internal bool QueueUserWorkItemInternal(WaitCallback callback, object context) {
         ThreadPoolWorkItem Item = new ThreadPoolWorkItem();

         Item._CallBack = callback;
         Item._Context = context;

         AddItem(ref Item);

         // LAMESPEC: Return value? should use exception here if anything goes wrong
         return true;
      }

      public static bool BindHandle(IntPtr osHandle) {
         throw new NotSupportedException("This is a win32 specific method, not supported Mono");
		}

		public static bool QueueUserWorkItem(WaitCallback callback) {
         return _Threadpool.QueueUserWorkItemInternal(callback);
		}

		public static bool QueueUserWorkItem(WaitCallback callback, object state) {
         return _Threadpool.QueueUserWorkItemInternal(callback, state);
		}

      public static bool UnsafeQueueUserWorkItem(WaitCallback callback, object state) {
         return _Threadpool.QueueUserWorkItemInternal(callback, state);
      }

      [MonoTODO]
		public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) {
			if (millisecondsTimeOutInterval < -1) {
				throw new ArgumentOutOfRangeException("timeout < -1");
			}

         throw new NotImplementedException();
      }

		[MonoTODO]
		public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) {
			if (millisecondsTimeOutInterval < -1) {
				throw new ArgumentOutOfRangeException("timeout < -1");
			}
		
         throw new NotImplementedException();
      }

		[MonoTODO]
		public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce) {
			// LAMESPEC: I assume it means "timeout" when it says "millisecondsTimeOutInterval"
			if (timeout.Milliseconds < -1) {
				throw new ArgumentOutOfRangeException("timeout < -1");
			}
			if (timeout.Milliseconds > Int32.MaxValue) {
				throw new NotSupportedException("timeout too large");
			}

         throw new NotImplementedException();
      }

      [CLSCompliant(false)][MonoTODO]
		public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) {
         throw new NotImplementedException();
      }

		[MonoTODO]
		public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) {
         throw new NotImplementedException();
      }

		[MonoTODO]
		public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) {
         throw new NotImplementedException();
		}

		[MonoTODO]
		public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce) {
         throw new NotImplementedException();
      }

		[CLSCompliant(false)][MonoTODO]
		public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) {
         throw new NotImplementedException();
      }
	}
}