-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
425 lines (399 loc) · 10.8 KB
/
ThreadPool.h
File metadata and controls
425 lines (399 loc) · 10.8 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
Copyright (c) 2015 Johnny Dickinson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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 OR COPYRIGHT HOLDERS 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.
*/
#pragma once
#include <memory>
#include <queue>
#include <vector>
#include <functional>
#include <utility>
#include <iostream>
#include "Semaphore.h"
//use Standard library thread when available
#define USE_STD_THREAD
//Visual Studio before 2012 doesn't have std::thread
#ifdef _MSC_VER
#if _MSC_VER < 1700
#undef USE_STD_THREAD
#endif
//no version of MSVC has thread_local
#define thread_local __declspec(thread)
#endif
//GCC < 4.8 doesn't have thread_local
#ifdef __GNUC__
#if __GNUC__ < 4 || __GNUC__ == 4 && __GNUC_MINOR__ < 8
#define thread_local __thread
#endif
#endif
#ifdef USE_STD_THREAD
#include <thread>
#include <mutex>
#define MUTEX std::unique_ptr<std::mutex>
#define NEW_MUTEX(m) m = std::unique_ptr<std::mutex>(new std::mutex)
#define ACQUIRE_MUTEX(m) m->lock()
#define TRY_MUTEX(m) m->try_lock()
#define RELEASE_MUTEX(m) m->unlock()
#define THREAD_ID thread::id
#define LPVOID void*
using std::thread;
#else
//no STL support for concurrency
#ifdef _WIN32
#define WIN32_CONCURRENCY
#include "windows.h"
#define MUTEX CRITICAL_SECTION
//#define NEW_MUTEX CreateMutex(NULL,FALSE,NULL)
#define NEW_MUTEX(m) InitializeCriticalSection(&m)
//#define ACQUIRE_MUTEX(m) while(WaitForSingleObject(m,INFINITE)!=0) { }
#define ACQUIRE_MUTEX(m) EnterCriticalSection(&m)
//#define TRY_MUTEX(m) 0==WaitForSingleObject(m,10)
#define TRY_MUTEX(m) TryEnterCriticalSection(&m)
//#define RELEASE_MUTEX(m) ReleaseMutex(m)
#define RELEASE_MUTEX(m) LeaveCriticalSection(&m)
#define THREAD_ID DWORD
typedef HANDLE thread;
#endif
#endif
template<typename T>
class Future{
protected:
struct Data{
Semaphore s;
bool complete;
T result;
Data():complete(false),s(0){
}
};
std::shared_ptr<Data> data;
public:
Future():data(new Data())
{}
inline void set(T val){
data->result = val;
data->complete = true;
data->s.post();
}
inline T operator=(T val){
set(val);
return val;
}
inline bool isDone(){
return data->complete;
}
inline T wait(){
while(!data->s.wait())
{}
data->s.post();
return data->result;
}
inline operator T(){
return wait();
}
};
template<typename T>
class Future<Future<T>>{
struct Data{
Semaphore s;
bool m_set;
Future<T> child;
Data():m_set(false),s(0){
}
};
std::shared_ptr<Data> data;
public:
Future():data(new Data)
{}
inline bool isDone(){
return data->m_set && data->child.isDone();
}
inline void set(const Future<T>& result)
{
data->child = result;
data->m_set = true;
data->s.post();
}
inline Future<T> wait(){
while(!data->s.wait())
{}
data->s.post();
return data->child;
}
inline operator Future<T>(){
return wait();
}
};
template<>
class Future<void>{
struct Data{
Semaphore s;
bool complete;
Data():complete(false),s(0){
}
};
std::shared_ptr<Data> data;
public:
Future():data(new Data())
{}
inline bool isDone(){
return data->complete;
}
inline void set(void)
{
data->complete = true;
data->s.post();
}
inline void wait(){
while(!data->s.wait())
{}
data->s.post();
}
};
struct WorkerThreadData{
public:
thread mthread;
THREAD_ID threadId;
MUTEX mutex;
bool blocked;
std::queue<std::function<void()>> workData;
WorkerThreadData(): blocked(false){
NEW_MUTEX(mutex);
}
#if _MSC_VER <= 1800
WorkerThreadData(WorkerThreadData&& rhs) : mthread(std::move(rhs.mthread))
, threadId(std::move(rhs.threadId))
, mutex(std::move(rhs.mutex))
, blocked(std::move(rhs.blocked))
, workData(std::move(rhs.workData))
{ }
#else
WorkerThreadData(WorkerThreadData&& rhs) = default;
#endif
#if _MSC_VER < 1700
private:
WorkerThreadData(const WorkerThreadData & rhs);
#else
WorkerThreadData(const WorkerThreadData & rhs) = delete;
#endif
};
struct DispatchData{
std::vector<WorkerThreadData> workerThreads;
std::queue<std::function<void()>> dispatchQueue;
MUTEX dispatchMutex;
Semaphore dispatchSemaphore;
bool stop;
DispatchData():dispatchSemaphore(0)
{}
};
template<typename T>
#ifdef USE_STD_THREAD
void awaitWorkerThreadProc(void* lpParameter){
#else
#ifdef _WIN32
DWORD WINAPI awaitWorkerThreadProc(LPVOID lpParameter){
#else
#error "Need thread invocation signature"
#endif
#endif
std::pair<std::shared_ptr<DispatchData>,Future<T>>* stuff = (std::pair<std::shared_ptr<DispatchData>,Future<T>>*)lpParameter;
//DispatchData* data = stuff->first;
while(true/*!stuff->second.complete()*/){
ACQUIRE_MUTEX(stuff->first->dispatchMutex);
if(!stuff->first->dispatchQueue.empty()){
std::function<void()> workUnit = stuff->first->dispatchQueue.front();
stuff->first->dispatchQueue.pop();
RELEASE_MUTEX(stuff->first->dispatchMutex);
workUnit();
} else {
RELEASE_MUTEX(stuff->first->dispatchMutex);
break; //no work to do, let this thread die
}
}
delete stuff;
#ifndef USE_STD_THREAD
return 0;
#endif
}
class ThreadPool{
private:
std::shared_ptr<DispatchData> sharedState;
public:
ThreadPool();
ThreadPool(int numberOfThreads);
~ThreadPool();
bool working(){
return sharedState->dispatchQueue.size() > 0;
}
void async(std::function<void()> workUnit);
template<typename T>
Future<T> async(std::function<T()> func){
Future<T> f;
async([f,func]()mutable{
f.set(func());
});
return f;
}
/*template<typename T>
Future<Future<T>> async(std::function<Future<T>()> func){
Future<T> f;
queue([f,func]()mutable{
Future<T> result = func();
f.set(result);
});
return f;
}*/
template<typename T>
T await(Future<T> result){
static thread_local int depth;
depth++; //track recursion depth
//TODO: put upper bound on recursion depth to prevent stack overflow (doesn't work yet)
if(depth >=100){
std::cout << "Warning: worker thread stack has become excessive" << std::endl;
}
while(!result.isDone() && !sharedState->stop){
//do some other work while we wait
if(TRY_MUTEX(sharedState->dispatchMutex)){
if(!sharedState->dispatchQueue.empty()){
std::function<void()> workUnit = sharedState->dispatchQueue.front();
sharedState->dispatchQueue.pop();
RELEASE_MUTEX(sharedState->dispatchMutex);
workUnit();
} else {
RELEASE_MUTEX(sharedState->dispatchMutex);
}
}
}
/*} else {
std::cout << "Warning: worker thread stack has become excessive" << std::endl;
//spawn a new worker thread so we don't blow out our stack
//auto data = make_pair(&sharedState,result);
std::pair<std::shared_ptr<DispatchData>,Future<T>>* data = new std::pair<std::shared_ptr<DispatchData>,Future<T>>;
data->first = sharedState;
data->second = result;
#ifdef WIN32_CONCURRENCY
thread worker = CreateThread(NULL,0,awaitWorkerThreadProc<T>,(LPVOID)data,0,NULL);
#else
thread worker(awaitWorkerThreadProc<T>,(LPVOID)data);
worker.detach();
#endif
//block on the return value rather than the other thread
//WaitForSingleObject(thread,INFINITE);
}*/
depth--;
//because result.done() is true it should be done now
return result.wait();
}
};
template<>
Future<void> ThreadPool::async<void>(std::function<void()> func);
class WorkQueue{
protected:
std::queue<std::function<void()>> workQueue;
MUTEX queueMutex;
public:
WorkQueue();
void async(std::function<void()> workUnit);
template<typename T>
Future<T> async(std::function<T()> func){
Future<T> f;
async([f,func]()mutable{
f.set(func());
});
return f;
}
template<typename T>
T await(Future<T> result) {
while (!result.isDone()) {
processQueueUnit();
}
return result.wait();
}
bool processQueueUnit(); //returns true if work was done
};
template<>
Future<void> WorkQueue::async<void>(std::function<void()> func);
#ifdef TEST
int fib(ThreadPool& pool, int x){
if(x < 2) {
return 1;
}
return pool.await(pool.async<int>([&pool,x]()->int{return fib(pool, x-1);}))
+ pool.await(pool.async<int>([&pool,x]()->int{return fib(pool, x-2);}));
}
bool testThreadpool(std::ostream& out){
WorkQueue mainQueue;
ThreadPool pool1(1);
ThreadPool pool2(32);
out << "Testing thread pool creation and deletion" << std::endl;
ThreadPool* pool3 = new ThreadPool();
delete pool3;
MUTEX blockStart;
NEW_MUTEX(blockStart);
ACQUIRE_MUTEX(blockStart);
int count = 0;
int count2 = 0;
bool success = true;
out << "test serial execution and basic use of Futures" << std::endl;
Future<bool> result1 = pool1.async<bool>([&blockStart,&out,&count]()->bool{
ACQUIRE_MUTEX(blockStart);
out << "result 1" << std::endl;
count++;
RELEASE_MUTEX(blockStart);
return count == 1;
});
pool1.async([&out,&count2](){
out << "result 2" << std::endl;
count2++;
});
Future<void> result3 = pool1.async<void>([&out,&count2](){
out << "result 3" << std::endl;
count2++;
});
success &= (count == 0);
success &= (count2 == 0);
out << "start: " << (success ? "true" : "false") << std::endl;
RELEASE_MUTEX(blockStart);
success &= result1.wait();
success &= (count == 1);
result3.wait();
success &= (count2 == 2);
out << "test parallel execution with an abusive workload and implicit conversion of Futures" << std::endl;
const int fibDepth = 20;
Future<int> output[fibDepth];
for (int i = 0; i < fibDepth; i++) {
output[i] = pool2.async<int>([&pool2, i]()->int {return fib(pool2, i); });
}
int correctVals[] = { 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765};
for (int i = 0; i < fibDepth; i++) {
//out << "status: " << (success ? "true" : "false") << std::endl;
out << i << " = " << /*pool2.await(output[i])*/output[i] << std::endl;
success &= (output[i].wait() == correctVals[i]);
}
out << "test WorkQueue and nested Futures" << std::endl;
int val = 0;
Future<Future<bool>> result = pool2.async<Future<bool>>([&]()->Future<bool>{
return mainQueue.async<bool>([&](){
val++;
return true;
});
});
success &= mainQueue.await(result);
success = (val == 1);
out << "finish: " << (success ? "true" : "false") << std::endl;
return success;
}
#endif