-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathThreadPool.cs
301 lines (274 loc) · 10.7 KB
/
ThreadPool.cs
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// ***************************************************************************
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org>
// ***************************************************************************
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace ThreadPooling
{
/// <summary>
/// This class implements a thread-pool. It buffers all the work items, which regrettably have to be classes, and
/// reuses them. It only cleans them up at
/// shutdown.
/// </summary>
public partial class ThreadPool
{
/// <summary>
/// The form of the callback delegate that carries the payload of the workItem.
/// </summary>
internal delegate object WorkItemCallback(object state);
/// <summary>
/// The callback function that should be called when the work item is finished.
/// </summary>
public delegate void CallbackFunction();
private bool isDisposeDoneWorkItemsAutomatically;
private readonly Queue<SingleThreadRunner> threads;
private readonly ConcurrentQueue<SingleThreadRunner> threadsIdle;
private int threadsWorking;
private readonly ConcurrentQueue<WorkItem> workItemQueue = new ConcurrentQueue<WorkItem>();
private readonly ConcurrentQueue<WorkItem> returnedWorkItems = new ConcurrentQueue<WorkItem>();
private bool shutDownSignaled;
private readonly object lockObjectShutDownSignaled = new object();
public int NumberOfThreads { get; }
/// <summary>
/// Gets or sets a value indicating whether this instance is set to dispose done work items automatically. Beware: If
/// you enable this option, the
/// dispose method of each work item is called immediately after its completion, thus destroying the reference. This
/// obviously is only an viable option
/// when using the action-interface (no return values) together with the <c>WaitForEveryWorkerIdle</c>-Method.
/// </summary>
/// <value>
/// <c>true</c> if this instance is dispose done work items automatically; otherwise, <c>false</c>.
/// </value>
public bool IsDisposeDoneWorkItemsAutomatically
{
get
{
Thread.MemoryBarrier();
return isDisposeDoneWorkItemsAutomatically;
}
set
{
isDisposeDoneWorkItemsAutomatically = value;
Thread.MemoryBarrier();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ThreadPool" /> class.
/// </summary>
public ThreadPool(int numberOfThreads, string threadsNamePrefix)
{
NumberOfThreads = numberOfThreads;
threads = new Queue<SingleThreadRunner>();
threadsIdle = new ConcurrentQueue<SingleThreadRunner>();
// allocate threads...
for (var i = 0; i < NumberOfThreads; i++)
{
var singleThreadRunner = new SingleThreadRunner(this);
singleThreadRunner.Thread = new Thread(singleThreadRunner.DoWork);
singleThreadRunner.Thread.Name = threadsNamePrefix + (i + 1);
singleThreadRunner.Thread.IsBackground = true;
threads.Enqueue(singleThreadRunner);
threadsIdle.Enqueue(singleThreadRunner);
singleThreadRunner.Thread.Start();
}
}
/// <summary>
/// Clears the work item queue.
/// </summary>
public void ClearWorkItemQueue()
{
WorkItem wi;
while (workItemQueue.TryDequeue(out wi))
{}
}
/// <summary>
/// The number of items that are still to be processed.
/// </summary>
/// <returns></returns>
public int NumberOfItemsLeft()
{
Thread.MemoryBarrier();
return workItemQueue.Count;
}
/// <summary>
/// The number of items that are done processing and returned.
/// </summary>
/// <returns></returns>
public int NumberOfItemsDone()
{
Thread.MemoryBarrier();
return returnedWorkItems.Count;
}
/// <summary>
/// Enqueues the work item.
/// </summary>
/// <param name="workItem">The work item.</param>
internal void EnqueueWorkItemInternal(WorkItem workItem)
{
// look for an idle worker...
SingleThreadRunner singleThreadRunner;
if (threadsIdle.TryDequeue(out singleThreadRunner))
{
// hand over the work item...
workItem.SingleThreadRunner = singleThreadRunner;
Interlocked.Increment(ref threadsWorking);
singleThreadRunner.SignalWork(workItem);
}
else
{
// just enqueue the item since all workers are busy...
workItemQueue.Enqueue(workItem);
}
}
/// <summary>
/// Dequeues the work item.
/// </summary>
/// <param name="singleThreadRunner">The single thread runner.</param>
/// <param name="isGetNewOne">
/// if set to <c>true</c> [is get new one].
/// </param>
/// <param name="returnedWorkItem">The returned work item.</param>
/// <returns>
/// <see langword="true" />, if a work item has been
/// successfully dequeued. <see langword="false" /> otherwise.
/// </returns>
internal WorkItem DequeueWorkItemInternal(SingleThreadRunner singleThreadRunner, bool isGetNewOne,
WorkItem returnedWorkItem = null)
{
if (returnedWorkItem != null)
{
returnedWorkItems.Enqueue(returnedWorkItem);
}
if (!shutDownSignaled && isGetNewOne)
{
WorkItem workItem;
if (workItemQueue.TryDequeue(out workItem))
{
workItem.SingleThreadRunner = singleThreadRunner;
return workItem;
}
}
// If we are here, there is no more work to do left...
// The worker has to be set to idle...
Interlocked.Decrement(ref threadsWorking);
threadsIdle.Enqueue(singleThreadRunner);
return null;
}
private WorkItem GetWorkItem(CallbackFunction asyncCallback)
{
WorkItem workItem;
if (!returnedWorkItems.TryDequeue(out workItem))
{
workItem = new WorkItem();
workItem.WorkItemStateTypeless = new WorkItemStateTypeless(workItem);
}
workItem.SingleThreadRunner = null;
workItem.IsCompleted = false;
workItem.Result = null;
workItem.AsyncCallback = asyncCallback;
return workItem;
}
/// <summary>
/// Returns the work item.
/// </summary>
/// <param name="returnedWorkItem">The returned work item.</param>
public void ReturnWorkItem(WorkItem returnedWorkItem)
{
returnedWorkItems.Enqueue(returnedWorkItem);
}
/// <summary>
/// Waits for the queue to empty.
/// </summary>
public void WaitForEveryWorkerIdle()
{
// A spinWait ensures a yield from time to time, forcing the CPU to do a context switch, thus allowing other processes to finish.
var spinWait = new SpinWait();
while (threadsWorking > 0)
{
Thread.MemoryBarrier();
spinWait.SpinOnce();
}
}
/// <summary>
/// Clears the work item cache of all returned and "to be reused" work items returned via the dispose-method of a
/// work-item-state-struct.
/// </summary>
public void ClearWorkItemCache()
{
WorkItem w;
while(returnedWorkItems.TryDequeue(out w))
{}
}
/// <summary>
/// Aborts all active threads.
/// </summary>
public void ShutDown()
{
// First, we want to close. So stop dealing new work items...
lock (lockObjectShutDownSignaled)
{
shutDownSignaled = true;
}
// signal the shutdown-command to all workers...
if (threads.Count > 0)
{
foreach (var thread in threads)
{
thread.SignalShutDown();
}
}
}
/// <summary>
/// Pauses all active threads.
/// </summary>
public void Sleep()
{
// signal the pause-command to all workers...
if (threads.Count > 0)
{
foreach (var thread in threads)
{
thread.SignalPause();
}
}
}
/// <summary>
/// Resumes all active threads.
/// </summary>
public void Wakeup()
{
// signal the resume-command to all workers...
if (threads.Count > 0)
{
foreach (var thread in threads)
{
thread.SignalResume();
}
}
}
}
}