-
Notifications
You must be signed in to change notification settings - Fork 0
/
world_clock.cpp
122 lines (88 loc) · 2.71 KB
/
world_clock.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 "world_clock.h"
WorldClock::WorldClock() {
time = 0;
externalEvents = 0;
externalEventsTotal = 0;
pthread_cond_init(&tickCond, NULL);
pthread_mutex_init(&tickMutex, NULL);
pthread_cond_init(&externalCond, NULL);
pthread_mutex_init(&externalMutex, NULL);
shouldRun = false;
}
void WorldClock::start() {
shouldRun = true;
pthread_create(&thread, NULL, WorldClock::threadHelper, this);
}
void WorldClock::registerExternalEvent() {
pthread_mutex_lock(&externalMutex);
externalEventsTotal += 1;
externalEvents += 1;
pthread_cond_broadcast(&externalCond);
pthread_mutex_unlock(&externalMutex);
}
void WorldClock::notifyExternalEvent() {
pthread_mutex_lock(&externalMutex);
externalEvents -= 1;
if( externalEvents <= 0 ) {
pthread_cond_broadcast(&externalCond);
}
pthread_mutex_unlock(&externalMutex);
}
void WorldClock::unregisterExternalEvent() {
pthread_mutex_lock(&externalMutex);
externalEventsTotal -= 1;
externalEvents -= 1;
if(externalEvents <= 0) {
pthread_cond_broadcast(&externalCond);
}
pthread_mutex_unlock(&externalMutex);
}
int WorldClock::waitForTick(int existingTime) {
pthread_mutex_lock(&tickMutex);
while( existingTime > time ) {
pthread_cond_wait(&tickCond, &tickMutex);
}
int newTime = time;
pthread_mutex_unlock(&tickMutex);
return newTime;
}
int WorldClock::getTime() {
return time;
}
void WorldClock::terminate() {
shouldRun = false;
pthread_mutex_lock(&externalMutex);
externalEventsTotal = 0;
externalEvents = 0;
pthread_cond_signal(&externalCond);
pthread_mutex_unlock(&externalMutex);
}
void WorldClock::cycle() {
timespec waitTime;
waitTime.tv_sec = 1;
waitTime.tv_nsec = 0;
clock_t startTime;
float elapsedTime = 0.0;
while(shouldRun) {
nanosleep(&waitTime, NULL);
startTime = clock();
pthread_mutex_lock(&externalMutex);
while( externalEvents > 0 ) {
pthread_cond_wait(&externalCond, &externalMutex);
}
pthread_mutex_unlock(&externalMutex);
time += 1;
pthread_mutex_lock(&externalMutex);
externalEvents = externalEventsTotal;
pthread_mutex_unlock(&externalMutex);
pthread_cond_broadcast(&tickCond);
elapsedTime = ((float)clock() - startTime)/CLOCKS_PER_SEC;
waitTime.tv_sec = 0;
waitTime.tv_nsec = (1.0 - elapsedTime) * 1000000000;
}
}
void* WorldClock::threadHelper(void* context) {
WorldClock* clock = (WorldClock*) context;
clock->cycle();
return NULL;
}