-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_task.cpp
More file actions
242 lines (219 loc) · 6.36 KB
/
test_task.cpp
File metadata and controls
242 lines (219 loc) · 6.36 KB
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
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdexcept>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include "assertion.h"
#include "decimal.h"
#include "promise.h"
#include "task.h"
using namespace std;
using namespace std::chrono;
using namespace kaiu;
Assertions assert({
{ nullptr, "Behaviour" },
{ "THREADS", "Callbacks are dispatched to correct threads" },
{ nullptr, "Calculate multiple factorials simultaneously" },
{ "625", "625!" },
{ "1250", "1250!" },
{ "2500", "2500!" },
{ "5000", "5000!" },
{ "10000", "10000!" },
{ nullptr, "Calculate a single factorial in parallel" },
{ "10001", "10001!" },
});
const auto cores = thread::hardware_concurrency() > 0 ? thread::hardware_concurrency() : 4;
ParallelEventLoop loop{ {
{ EventLoopPool::reactor, 1 },
{ EventLoopPool::interaction, 1 },
{ EventLoopPool::calculation, cores }
} };
void threadTests()
{
atomic<bool> done{false};
mutex mx;
condition_variable cv;
const auto doReaction = [&] (int result) {
if (result != 42) {
assert.fail("THREADS", "Result incorrect");
}
if (ParallelEventLoop::current_pool() != EventLoopPool::reactor) {
assert.fail("THREADS", "Reaction in wrong pool");
}
assert.pass("THREADS");
};
auto handler = [&] (exception_ptr) {
if (ParallelEventLoop::current_pool() != EventLoopPool::reactor) {
assert.fail("THREADS", "Reaction (handler) in wrong pool");
}
assert.fail("THREADS", "Exception thrown");
};
auto finalizer = [&] () {
if (ParallelEventLoop::current_pool() != EventLoopPool::reactor) {
assert.fail("THREADS", "Reaction (finalizer) in wrong pool");
}
done = true;
cv.notify_all();
};
const auto doCalculation = [&] () {
if (ParallelEventLoop::current_pool() != EventLoopPool::calculation) {
assert.fail("THREADS", "Action in wrong pool");
}
Promise<int> promise;
/* Asynchronous */
loop.push(EventLoopPool::calculation,
[=] (EventLoop&) {
this_thread::sleep_for(10ms);
promise->resolve(42);
});
return promise;
};
const auto handleInteraction = [&] (EventLoop& loop) {
if (ParallelEventLoop::current_pool() != EventLoopPool::interaction) {
assert.fail("THREADS", "Initial job in wrong pool");
}
const auto task = promise::task(promise::Factory<int>(doCalculation),
EventLoopPool::calculation, EventLoopPool::reactor) << ref(loop);
task()
->then(doReaction, handler, finalizer);
};
loop.push(EventLoopPool::interaction, handleInteraction);
unique_lock<mutex> lock(mx);
cv.wait(lock, [&done] { return bool(done); });
}
void behaviourTests()
{
threadTests();
}
string writeStrFunc(const string& message)
{
//cout << message << endl;
return message;
}
decimal writeNumFunc(const decimal& value)
{
cout << "\t" << string(value) << endl;
return value;
}
decimal factorial(const decimal& x)
{
return !x;
}
decimal partial_factorial(const decimal& x, const decimal& offset, const decimal& step)
{
if (offset > x) {
return decimal(1);
}
decimal r(offset);
for (decimal i = offset + step; i <= x; i += step) {
r *= i;
}
return r;
}
decimal partial_factorial_tuple(const tuple<decimal, decimal, decimal>& range)
{
return partial_factorial(get<0>(range), get<1>(range), get<2>(range));
}
string format_result(const time_point<system_clock>& start, const int& i, const decimal& result)
{
const auto duration =
duration_cast<microseconds>(system_clock::now() - start);
const string note =
to_string(result.length()) + " digits \t" +
"+" + to_string(duration.count() / 1000) + "ms \t" +
to_string(duration.count() / result.length()) + "μs/digit";
assert.pass(to_string(i), note);
return to_string(i) + "! = " + note;
}
decimal series_product(const vector<decimal>& series)
{
if (series.size() == 0) {
throw invalid_argument("Product of empty series");
}
decimal reductor{series[0]};
bool first = true;
for (const auto& value : series) {
if (first) {
first = false;
continue;
}
reductor = decimal::parallel_multiply(reductor, value);
//reductor *= value;
}
return reductor;
}
void print_error(exception_ptr error)
{
try {
rethrow_exception(error);
} catch (const exception& e) {
cerr << "Exception! Message: " << e.what() << endl;
}
}
const auto writeStr = promise::dispatchable(writeStrFunc,
EventLoopPool::interaction, EventLoopPool::reactor) << ref(loop);
const auto writeNum = promise::dispatchable(writeNumFunc,
EventLoopPool::interaction, EventLoopPool::reactor) << ref(loop);
const auto calcFactorial = promise::dispatchable(factorial,
EventLoopPool::calculation, EventLoopPool::reactor) << ref(loop);
const auto calcPartialFactorial = promise::dispatchable(partial_factorial_tuple,
EventLoopPool::calculation, EventLoopPool::reactor) << ref(loop);
const auto formatResult = promise::dispatchable(format_result,
EventLoopPool::interaction, EventLoopPool::reactor) << ref(loop);
const auto seriesProduct = promise::dispatchable(series_product,
EventLoopPool::calculation, EventLoopPool::reactor) << ref(loop);
void calculateMultipleFactorials()
{
/*
* Use decimal class to calculate big factorials then display their
* lengths
*/
const auto start = system_clock::now();
/* Calculate multiple factorials */
for (int i = 625; i <= 10000; i *= 2) {
promise::resolved(int(i))
->then(calcFactorial)
->then(formatResult << cref(start) << i)
->then(writeStr)
->finish();
}
loop.join(print_error);
}
void calculateOneFactorial()
{
/* Calculate one huge factorial */
const auto tasks = cores >= 8 ? 8 : (cores + 1);
const int x = 10001;
vector<Promise<decimal&&>> partials;
partials.reserve(tasks);
const auto start = system_clock::now();
for (remove_const<decltype(tasks)>::type i = 0; i < tasks; i++) {
auto subrange = make_tuple(x, i + 1, tasks);
partials.push_back(
promise::resolved(move(subrange))
->then(calcPartialFactorial));
}
promise::combine(partials)
->then(seriesProduct)
->then(formatResult << cref(start) << x)
->then(writeStr)
->finish();
// using namespace kaiu::task_monad;
// promise::combine(partials) | seriesProduct | formatResult << cref(start) << x | writeStr;
loop.join(print_error);
}
int main(int argc, char *argv[])
try {
behaviourTests();
calculateMultipleFactorials();
calculateOneFactorial();
/* Wait for detatched threads to complete, TODO use OS wait instead */
this_thread::sleep_for(100ms);
return assert.print(argc, argv);
} catch (...) {
assert.print_error();
}