-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathThreadMgr.cpp
122 lines (103 loc) · 2.4 KB
/
ThreadMgr.cpp
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
#include <Windows.h>
#include "ThreadMgr.h"
#include <tlhelp32.h>
#include "Utils.h"
ThreadMgr::ThreadMgr()
{
}
ThreadMgr::~ThreadMgr()
{
}
bool ThreadMgr::addAllThreads(DWORD excluded)
{
MutexGuard guard(&_lock);
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hSnapshot != INVALID_HANDLE_VALUE) {
THREADENTRY32 te;
te.dwSize = sizeof(te);
if (Thread32First(hSnapshot, &te)) {
do {
if (te.th32OwnerProcessID == GetCurrentProcessId()) {
if (te.th32ThreadID == excluded)
continue;
addThread(te.th32ThreadID);
}
te.dwSize = sizeof(te);
} while (Thread32Next(hSnapshot, &te));
}
CloseHandle(hSnapshot);
}
return true;
}
void ThreadMgr::clearThreads()
{
MutexGuard guard(&_lock);
std::map<DWORD, HANDLE>::iterator it;
for (it = _threads.begin(); it != _threads.end(); it++) {
CloseHandle(it->second);
}
_threads.clear();
}
HANDLE ThreadMgr::addThread(DWORD tid)
{
HANDLE hThread = openThread(THREAD_ALL_ACCESS, FALSE, tid);
if (hThread == NULL) {
MyTrace("%s(): openThread() failed. errno: %x", __FUNCTION__, GetLastError());
assert(false);
hThread = (HANDLE)-1;
}
MutexGuard guard(&_lock);
_threads[tid] = hThread;
return hThread;
}
bool ThreadMgr::delThread(DWORD tid)
{
MutexGuard guard(&_lock);
std::map<DWORD, HANDLE>::iterator it = _threads.find(tid);
if (it == _threads.end()) {
return false;
}
if (it->second && it->second != (HANDLE)-1)
CloseHandle(it->second);
_threads.erase(it);
return true;
}
void ThreadMgr::suspendAll(DWORD excluded)
{
MutexGuard guard(&_lock);
std::map<DWORD, HANDLE>::iterator it;
for (it = _threads.begin(); it != _threads.end(); it++) {
if (it->first == excluded)
continue;
suspendThread(it->second);
}
}
void ThreadMgr::resumeAll(DWORD excluded)
{
MutexGuard guard(&_lock);
std::map<DWORD, HANDLE>::iterator it;
for (it = _threads.begin(); it != _threads.end(); it++) {
if (it->first == excluded)
continue;
resumeThread(it->second);
}
}
HANDLE ThreadMgr::threadIdToHandle(DWORD tid)
{
MutexGuard guard(&_lock);
std::map<DWORD, HANDLE>::iterator it;
it = _threads.find(tid);
if (it == _threads.end())
return NULL;
return it->second;
}
DWORD ThreadMgr::threadHandleToId(HANDLE handle)
{
MutexGuard guard(&_lock);
std::map<DWORD, HANDLE>::iterator it;
for (it = _threads.begin(); it != _threads.end(); it++) {
if (it->second == handle)
return it->first;
}
return 0;
}