-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
executable file
·297 lines (251 loc) · 8.52 KB
/
main.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
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
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable_ex.h>
using namespace gecaib;
std::ostream &operator<<(std::ostream &out, const cv_status_ex value)
{
static std::map<cv_status_ex, std::string> strings;
if (strings.size() == 0)
{
#define INSERT_ELEMENT(p) strings[p] = #p
INSERT_ELEMENT(cv_status_ex::timeout);
INSERT_ELEMENT(cv_status_ex::signaled);
INSERT_ELEMENT(cv_status_ex::predicate);
#undef INSERT_ELEMENT
}
return out << strings[value];
}
std::ostream &operator<<(std::ostream &out, const cv_status value)
{
static std::map<cv_status, std::string> strings;
if (strings.size() == 0)
{
#define INSERT_ELEMENT(p) strings[p] = #p
INSERT_ELEMENT(cv_status::timeout);
INSERT_ELEMENT(cv_status::no_timeout);
#undef INSERT_ELEMENT
}
return out << strings[value];
}
// working thread stuff
std::mutex m;
condition_variable_ex cv;
std::mutex m_done;
condition_variable_ex cv_done;
bool done = false;
bool ready = false;
bool processed = false;
cv_status_ex finalStatus;
// bgnd working thread test stuff
std::mutex m_working;
bool working = false;
condition_variable_ex cv_working;
bool started = false;
condition_variable_ex cv_started;
bool awake_thread = false;
// multithreaded protected cout
class CoutThread : public std::ostringstream
{
public:
CoutThread() = default;
~CoutThread()
{
std::lock_guard<std::mutex> guard(_mutexPrint);
cout << getCurrentTimestamp() << ": " << this->str();
}
std::string getCurrentTimestamp()
{
using std::chrono::system_clock;
auto currentTime = std::chrono::system_clock::now();
char buffer[120];
auto transformed = currentTime.time_since_epoch().count() / 1000000;
auto millis = transformed % 1000;
std::time_t tt;
tt = system_clock::to_time_t(currentTime);
auto timeinfo = localtime(&tt);
strftime(buffer, 120, "%H:%M:%S", timeinfo);
sprintf(&(buffer[strlen(buffer)]), ":%03d", (int)millis);
return std::string(buffer);
}
private:
static std::mutex _mutexPrint;
};
std::mutex CoutThread::_mutexPrint{};
// rand[0,1]
double randd()
{
return (double)rand() / (double)RAND_MAX;
}
// test 1
void worker_thread(int timeout)
{
ready = false;
auto predicate = []
{ return ready; };
// Wait until main() sends data
std::unique_lock lk(m);
finalStatus = cv.wait_for_ex(lk, chrono::milliseconds(timeout), predicate);
ready = false;
// after the wait, we own the lock.
CoutThread{} << "Wait finished: " << finalStatus << "\n";
// Send data back to main()
processed = true;
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
cv_done.notify_one();
}
void signaler_thread(int timeout)
{
CoutThread{} << "signaler waiting " << timeout << "ms\n";
this_thread::sleep_for(chrono::milliseconds(timeout));
cv.notify_all();
CoutThread{} << "signaled\n";
}
void predicater_thread(int timeout)
{
CoutThread{} << "predicater waiting " << timeout << "ms\n";
this_thread::sleep_for(chrono::milliseconds(timeout));
std::lock_guard lk(m);
ready = true;
CoutThread{} << "predicated\n";
}
// test 2
void bgnd_worker_thread(int timeout)
{
// the predicate can depends on the main work
auto predicate = []
{ return awake_thread; };
// simulate thread creation delay
auto th_start_delay = (int)(timeout / 2 * randd());
this_thread::sleep_for(chrono::milliseconds(th_start_delay));
// notify thread started
CoutThread{} << "bgnd started in " << th_start_delay << endl;
std::unique_lock lkw(m_working);
started = true;
cv_started.notify_all();
// simulate thread initialization delay
auto th_init_delay = (int)(timeout / 2 * randd());
this_thread::sleep_for(chrono::milliseconds(th_init_delay));
CoutThread{} << "bgnd initialized in " << th_init_delay << endl;
// test distinct timeout relations
auto th_timeout = timeout / 2;
if (randd() > .5)
{
th_timeout = randd() * timeout;
}
while (true)
{
// wait with timeout and predicate
CoutThread{} << "bgnd sleeping for " << th_timeout << "ms " << endl;
auto finalStatus = cv_working.wait_for_ex(lkw, chrono::milliseconds(th_timeout), predicate);
if (finalStatus == cv_status_ex::signaled || !working)
{
CoutThread{} << "bgnd exitting thread. wait status: " << finalStatus << ". working: " << working << endl;
break;
}
CoutThread{} << "bgnd continue working. wait status: " << finalStatus << ". working: " << working << endl;
// do some work
CoutThread{} << "bgnd working" << endl;
this_thread::sleep_for(chrono::milliseconds((int)(timeout / 2 * randd())));
awake_thread = false;
}
}
int main(int n, char **args)
{
/* Intializes random number generator */
time_t t;
srand((unsigned) time(&t));
int type = atoi(args[1]);
int repeat = atoi(args[2]);
CoutThread{} << "test type: " << type << " num repeat: " << repeat << endl;
if (type == 1)
{
cv_status_ex desiredStatus = (cv_status_ex)atoi(args[3]);
int thread_timeout = atoi(args[4]);
int signal_timeout = atoi(args[5]);
int predicate_timeout = atoi(args[6]);
CoutThread{} << "thread_timeout: " << thread_timeout << " signal_timeout: " << signal_timeout << " predicate_timeout: " << predicate_timeout << "\n";
for (int i = 0; i < repeat; i++)
{
CoutThread{} << "******** " << i << " ********" << endl;
/**
* worker thread test.
*/
std::thread worker(worker_thread, thread_timeout);
std::thread signaler(signaler_thread, signal_timeout);
std::thread predicater(predicater_thread, predicate_timeout);
// wait for the worker
{
std::unique_lock lk(m_done);
cv_done.wait(lk, []
{ return processed; });
}
worker.join();
signaler.join();
predicater.join();
if (desiredStatus != finalStatus)
{
CoutThread{} << "Failed: it should be " << desiredStatus << " and is " << finalStatus << "\n";
return 1;
}
CoutThread{} << endl;
}
return 0;
}
else if (type == 2)
{
int loop_timeout = atoi(args[3]);
/**
* Background worker thread test.
*/
for (int i = 0; i < repeat; i++)
{
CoutThread{} << "******** " << i << " ********" << endl;
CoutThread{} << "loop_timeout: " << loop_timeout << endl;
awake_thread = false;
working = true;
started = false;
std::thread bgnd_worker(bgnd_worker_thread, loop_timeout);
// wait for thread to be ready
{
CoutThread{} << "main program waithing thread ready" << endl;
std::unique_lock lk(m_working);
cv_started.wait(lk, [] { return started; });
}
// do some work
int workTime = (int)(loop_timeout * (randd()));
CoutThread{} << "main program do some work " << workTime << "ms " << endl;
this_thread::sleep_for(chrono::milliseconds(workTime));
if (randd() > .5)
{
// ..and awake the thread
CoutThread{} << "main program change predicate" << endl;
awake_thread = true;
if (randd() > .5)
{
// ..and some more work
workTime = (int)(loop_timeout * (randd()));
CoutThread{} << "main program do some more work " << workTime << "ms " << endl;
this_thread::sleep_for(chrono::milliseconds(workTime));
}
}
// stop and join thread
CoutThread{} << "main program exiting" << endl;
std::unique_lock<std::mutex> lck(m_working);
working = false;
lck.unlock();
cv_working.notify_all();
CoutThread{} << "main waiting thread" << endl;
bgnd_worker.join();
CoutThread{} << "joined " << i << endl
<< endl;
}
}
return 0;
};