This repository has been archived by the owner on Dec 18, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vgm_threads.cpp
109 lines (100 loc) · 2.27 KB
/
vgm_threads.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
#include "vgm_threads.h"
std::vector<HostnameFetcher *> Resolvers;
CriticalSection::CriticalSection() {
InitializeCriticalSection(&handle);
}
CriticalSection::CriticalSection(CRITICAL_SECTION& _handle) : handle(_handle) {
}
CriticalSection::~CriticalSection() {
DeleteCriticalSection(&handle);
}
void CriticalSection::enter() {
EnterCriticalSection(&handle);
}
void CriticalSection::leave() {
LeaveCriticalSection(&handle);
}
CriticalSectionEntry::CriticalSectionEntry(CriticalSection& _criticalSection) : criticalSection(_criticalSection) {
criticalSection.enter();
}
CriticalSectionEntry::~CriticalSectionEntry() {
criticalSection.leave();
}
Event::Event(bool initialState, bool manualReset) {
handle = CreateEvent(NULL, manualReset, initialState, NULL);
}
void Event::wait(int timeout) {
WaitForSingleObject(handle, timeout);
}
void Event::set() {
SetEvent(handle);
}
void Event::reset() {
ResetEvent(handle);
}
void Event::pulse() {
PulseEvent(handle);
}
TaskList::TaskList() : hasPendingTasks(false, true) {
isRunning = false;
}
TaskList::~TaskList() {
}
void TaskList::add(Task& task) {
CriticalSectionEntry lockEntry(lock);
tasks.push_back(&task);
hasPendingTasks.set();
}
void TaskList::execute() {
CriticalSectionEntry lockEntry(lock);
while (isRunning) {
if (!tasks.empty()) {
Task* task = tasks.front();
tasks.pop_front();
lock.leave();
task->perform();
delete task; // TODO: dirty.
lock.enter();
if (tasks.empty()) { hasPendingTasks.reset(); }
}
lock.leave();
hasPendingTasks.wait();
lock.enter();
}
}
void TaskList::start() {
isRunning = true;
execute();
}
void TaskList::stop() {
isRunning = false;
}
Thread::Thread() {
isRunning = false;
}
Thread::~Thread() {
stop();
wait();
}
int __cdecl Thread::ThreadMain(LPVOID parameter) {
((Thread*)parameter)->execute();
return true;
}
void Thread::start() {
isRunning = true;
handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadMain, this, CREATE_SUSPENDED, (LPDWORD)&id);
ResumeThread(handle);
}
void Thread::stop() {
isRunning = false;
}
bool Thread::wait(int timeout) {
return WaitForSingleObject(handle, timeout) == WAIT_OBJECT_0;
}
HostnameFetcher::HostnameFetcher() {
Resolved = -1;
Resolvers.push_back(this);
}
HostnameFetcher::~HostnameFetcher() {
delete this->HostConnection;
}