-
Notifications
You must be signed in to change notification settings - Fork 18
/
pool.h
100 lines (83 loc) · 1.48 KB
/
pool.h
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
//
#include <queue>
class TPOOL
{
private:
bool Ending = false;
class TTHREAD
{
public:
TPOOL* p = 0;
HANDLE hE2 = 0;
HANDLE hM = 0;
std::function<void()> f;
void thr()
{
for (;;)
{
HANDLE hh[2] = { hM,hE2 };
auto wi = WaitForMultipleObjects(2,hh,false,INFINITE);
if (wi == WAIT_OBJECT_0 + 1)
break;
if (f)
f();
f = nullptr;
ReleaseMutex(hM);
}
}
void start(TPOOL* pp)
{
p = pp;
hM = CreateMutex(0, TRUE, 0);
hE2 = CreateEvent(0, 0, 0, 0);
std::thread t(&TTHREAD::thr, this);
t.detach();
}
};
std::vector<HANDLE> mutexes;
std::vector<std::shared_ptr<TTHREAD>> threads;
std::queue<std::function<void()>> q;
public:
TPOOL()
{
}
void End()
{
Join();
Ending = true;
for(auto& t : threads)
SetEvent(t->hE2);
Join();
}
void Init(size_t mt = 1)
{
threads.resize(mt);
for (auto& t : threads)
{
t = std::make_shared<TTHREAD>();
t->start(this);
mutexes.push_back(t->hM);
}
}
HRESULT Add(std::function<void()> f)
{
// Instant run
DWORD e = WaitForMultipleObjects(mutexes.size(), mutexes.data(), FALSE, 0);
if (e == WAIT_FAILED)
return E_FAIL;
if (e != WAIT_TIMEOUT)
{
size_t idx = e - WAIT_OBJECT_0;
threads[idx]->f = f;
ReleaseMutex(threads[idx]->hM);
ReleaseMutex(threads[idx]->hM);
return S_OK;
}
q.push(f);
return S_FALSE;
}
void Join()
{
WaitForMultipleObjects(mutexes.size(), mutexes.data(), TRUE, INFINITE);
}
};