-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
457 lines (419 loc) · 21.7 KB
/
Copy pathmain.cpp
File metadata and controls
457 lines (419 loc) · 21.7 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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/**
* The idea is to construct a simple reflection tool to reflect on
* resource usage and how they are accessed (read or write mode).
* It is basically a list of all accessed resources of one routine,
* including accessed resources of all sub-routines.
* So when I define a task for a multithreaded system, I only list accessed
* resources and called functions without the need to manually go into every
* function to check on used resources.
*/
#include <functional>
#include <iostream>
#include <Meta.hpp>
#include <queue>
#include <thread>
#include <vector>
#include "MetaResourceList.h"
#include "MetaTask.hpp"
#include "MetaThreadPool.hpp"
int main()
{
/***************
* Static tests
***************/
// check global registered resources
static_assert(Meta::TypeListSize(Meta::TGlobalResourceList{}) > 0);
// check members via C++26 reflection
using TMode = Meta::EResourceAccessMode;
static_assert(std::is_same_v<typename [:std::meta::type_of(CFoo::CMeta::TNumber<TMode::READ>::MEMBER_INFO):], int>);
static_assert(std::meta::identifier_of(CFoo::CMeta::TNumber<TMode::READ>::MEMBER_INFO) == std::string_view("number"));
static_assert(std::is_same_v<typename [:std::meta::type_of(CBar::CMeta::TSomeNumber<TMode::READ>::MEMBER_INFO):], int>);
static_assert(std::is_same_v<typename [:std::meta::type_of(CBar::CMeta::TSomeString<TMode::READ>::MEMBER_INFO):],std::string>);
static_assert(std::is_same_v<typename [:std::meta::type_of(CBar::CMeta::TAnotherString<TMode::READ>::MEMBER_INFO):],std::string>);
static_assert(
std::meta::identifier_of(CBar::CMeta::TAnotherString<TMode::READ>::MEMBER_INFO)
== std::string_view("anotherString")
);
// define aliases to check
using TSomeNumberWrite = CBar::CMeta::TSomeNumber<TMode::WRITE>;
using TSomeStringRead = CBar::CMeta::TSomeString<TMode::READ>;
using TSomeStringWrite = CBar::CMeta::TSomeString<TMode::WRITE>;
using TAnotherStringWrite = CBar::CMeta::TAnotherString<TMode::WRITE>;
using TSomeMethodResources = Meta::CMethodResources<TSomeNumberWrite, TSomeStringWrite>;
using TFooBarNumRead = IFooBar::CMeta::TFooBarNum<TMode::READ>;
using TFooBarNumWrite = IFooBar::CMeta::TFooBarNum<TMode::WRITE>;
using TBarFooNumRead = CBarFoo::CMeta::TBarFooNum<TMode::READ>;
using TOtherFooBarNumWrite = CFooBar::CMeta::TOtherFooBarNum<TMode::WRITE>;
// check TUniqueTypes
static_assert(std::is_same_v<Meta::TUniqueTypes<TSomeStringRead, TSomeStringRead, TSomeStringWrite>,
// order is inverse, filters out 1x TSomeStringRead
Meta::CFilteredUniqueTypeList<TSomeStringWrite, TSomeStringRead>>);
// check concept exist_write_access
static_assert(Meta::exist_write_access<TSomeStringRead, TSomeStringWrite>);
// check TResourceTypes
static_assert(std::is_same_v<Meta::TResourceTypes<TSomeStringRead, TSomeStringWrite>,
Meta::CFilteredResourceTypeList<TSomeStringWrite>>); // filters out TSomeStringRead
static_assert(std::is_same_v<Meta::TResourceTypes<TSomeStringWrite, TSomeStringRead>::TTypes, // different order
Meta::CTypeList<TSomeStringWrite>>); // filters out TSomeStringRead
static_assert(std::is_same_v<decltype(
Meta::CMethodResources<TSomeStringRead, TSomeStringWrite>
::GetFilteredResources()
),
Meta::CTypeList<TSomeStringWrite>>); // filters out TSomeStringRead
static_assert(std::is_same_v<decltype(
Meta::CMethodResources<TSomeStringWrite, TSomeStringRead> // different order
::GetFilteredResources()
),
Meta::CTypeList<TSomeStringWrite>>); // filters out TSomeStringRead
// check Methods have the right resources
static_assert(std::is_same_v<decltype(CFoo::CMeta::TMethodA::GetFilteredResources()),
Meta::CTypeList<CFoo::CMeta::TNumber<TMode::WRITE>,
TSomeNumberWrite,
TSomeStringRead>>);
static_assert(std::is_same_v<decltype(CFoo::CMeta::TMethodB::GetFilteredResources()),
Meta::CTypeList<TSomeNumberWrite,
TSomeStringWrite>>);
static_assert(std::is_same_v<decltype(CFoo::CMeta::TMethodC::GetFilteredResources()),
Meta::CTypeList<TSomeNumberWrite,
TSomeStringWrite,
TAnotherStringWrite>>);
static_assert(std::is_same_v<decltype(IFooBar::CMeta::TAbstractMethod::GetFilteredResources()),
Meta::CTypeList<TBarFooNumRead,
TFooBarNumWrite>>);
static_assert(std::is_same_v<decltype(IFooBar::CMeta::TVirtualMethod::GetFilteredResources()),
Meta::CTypeList<TOtherFooBarNumWrite,
TFooBarNumRead,
TFooBarNumRead>>);
// check recursion (by mixing a CMethodResources' param pack with a CMethodResources and a CMemberResourceAccess)
using TRecursiveMethodResources = Meta::CMethodResources<TSomeMethodResources, TSomeStringRead>;
static_assert(std::is_same_v<decltype(TRecursiveMethodResources::GetResources()),
Meta::CTypeList<TSomeNumberWrite, TSomeStringWrite, TSomeStringRead>>);
static_assert(std::is_same_v<decltype(TRecursiveMethodResources::GetFilteredResources()),
Meta::CTypeList<TSomeNumberWrite, TSomeStringWrite>>); // filters out TSomeStringRead
// Retrieve filtered resources
// type: Meta::CTypeList<CResourceAccess<^^CBar::someNumber, Meta::EResourceAccessMode::WRITE>, // TSomeNumberWrite
// CResourceAccess<^^CBar::someString, Meta::EResourceAccessMode::WRITE>> // TSomeStringWrite
constexpr auto barMethod = Meta::Bar::MMethod::GetFilteredResources();
static_assert(std::is_same_v<std::decay_t<decltype(barMethod)>,
Meta::CTypeList<TSomeNumberWrite,
TSomeStringWrite>>);
static_assert( // CResourceAccess<^^CBar::someNumber, Meta::EResourceAccessMode::WRITE>
Meta::TypeListAt<0>(barMethod).ACCESS_MODE == TMode::WRITE
);
static_assert( // CResourceAccess<^^CBar::someString, Meta::EResourceAccessMode::WRITE>
Meta::TypeListAt<1>(barMethod).ACCESS_MODE == TMode::WRITE
);
// input types: Meta::CTypeList<CSomeNumber<EResourceAccessMode::WRITE>, // TSomeNumberWrite
// CSomeString<EResourceAccessMode::WRITE>, // TSomeStringWrite
// CSomeString<EResourceAccessMode::READ>, // TSomeStringRead
// CSomeString<EResourceAccessMode::READ>, // TSomeStringRead
// CAnotherString<EResourceAccessMode::WRITE>> // TAnotherStringWrite
// ---------------------------------------------------------------------------------------------
// filtered types: Meta::CTypeList<CSomeNumber<EResourceAccessMode::WRITE>, // TSomeNumberWrite
// CSomeString<EResourceAccessMode::WRITE>, // TSomeStringWrite
// CAnotherString<EResourceAccessMode::WRITE>> // TAnotherStringWrite
constexpr auto fooMethodC = Meta::Foo::MMethodC::GetFilteredResources();
static_assert(std::is_same_v<std::decay_t<decltype(fooMethodC)>,
Meta::CTypeList<TSomeNumberWrite,
TSomeStringWrite,
TAnotherStringWrite>>);
static_assert( // CSomeNumber<EResourceAccessMode::WRITE>
Meta::TypeListAt<0>(fooMethodC).ACCESS_MODE == TMode::WRITE
);
// Use Meta helper method to check resources
static_assert(
Meta::is_same_method_resources(CFoo::CMeta::TMethodA{},
Meta::CMethodResources<CFoo::CMeta::TNumber<TMode::WRITE>,
TSomeNumberWrite,
TSomeStringRead>{})
);
// different orders
static_assert(
Meta::is_same_method_resources(CFoo::CMeta::TMethodA{},
Meta::CMethodResources<TSomeNumberWrite,
CFoo::CMeta::TNumber<TMode::WRITE>,
TSomeStringRead>{})
);
static_assert(
Meta::is_same_method_resources(CFoo::CMeta::TMethodA{},
Meta::CMethodResources<TSomeNumberWrite,
TSomeStringRead,
CFoo::CMeta::TNumber<TMode::WRITE>>{})
);
// Check annotations
using TAnnotationOfFooMethodA = Meta::TAnnotation<^^CFoo::MethodA>;
using TAnnotationOfFooMethodB = Meta::TAnnotation<^^CFoo::MethodB>;
using TAnnotationOfFooMethodC = Meta::TAnnotation<^^CFoo::MethodC>;
using TAnnotationOfFooBarVirtualMethod = Meta::TAnnotation<^^IFooBar::VirtualMethod>;
static_assert(std::is_same_v<TAnnotationOfFooMethodA, CFoo::CMeta::TMethodA>);
static_assert(std::is_same_v<TAnnotationOfFooMethodB, CFoo::CMeta::TMethodB>);
static_assert(std::is_same_v<TAnnotationOfFooMethodC, CFoo::CMeta::TMethodC>);
static_assert(std::is_same_v<TAnnotationOfFooBarVirtualMethod, IFooBar::CMeta::TVirtualMethod>);
// Compile-time conflict checks against the example tasks (A/B/C/D/E).
static_assert(Meta::methods_conflict<Meta::Foo::MReadSomeString, Meta::Bar::MMethod>()); // A vs B
static_assert(!Meta::methods_conflict<Meta::Foo::MReadSomeString, Meta::Bar::MSetAnotherString>()); // A vs C
static_assert(!Meta::methods_conflict<Meta::Bar::MMethod, Meta::Bar::MSetAnotherString>()); // B vs C
static_assert(!Meta::methods_conflict<Meta::CNoResources, Meta::Foo::MReadSomeString>()); // D vs A
static_assert(Meta::methods_conflict<Meta::Foo::MMethodA, Meta::Foo::MReadSomeString>()); // E (Foo::number) vs A
static_assert(Meta::methods_conflict<Meta::Foo::MMethodA, Meta::Bar::MMethod>()); // E vs B
static_assert(Meta::methods_conflict<Meta::Foo::MMethodC, Meta::Bar::MSetAnotherString>()); // E vs C
// CNoResources never conflicts with anything, including itself
static_assert(!Meta::methods_conflict<Meta::CNoResources, Meta::CNoResources>());
/***************
* Runtime tests
***************/
// Create our test objects
auto myFoo = std::make_unique<CFoo>();
auto myBar = std::make_unique<CBar>();
// Create some tasks
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; // nanoseconds, system_clock, seconds
auto sleepDuration = nanoseconds(1000);
auto sleepDurationD = seconds(1);
// Task A
// Write accesses: Foo::number
// Read accesses: Bar::someString
std::function funA = [&]()
{
std::cout << "Execute function A\n";
sleep_for(sleepDuration);
myFoo->ReadSomeString(*myBar);
sleep_for(sleepDuration);
std::cout << "Function A end\n";
};
// type Meta::CTypeList< struct Meta::Bar::CSomeString<0>, struct Meta::Foo::CNumber<1> >
using TTaskA = Meta::CTask<Meta::Foo::MReadSomeString>;
auto taskA = std::make_shared<TTaskA>(std::move(funA));
// Task B
// Write accesses: Bar::someNumber and Bar::someString
// Read accesses: none
std::function funB = [&]()
{
std::cout << "Execute function B\n";
sleep_for(sleepDuration);
myBar->Method();
sleep_for(sleepDuration);
std::cout << "Function B end\n";
};
// type Meta::CTypeList< struct Meta::Bar::CSomeString<1>, struct Meta::Bar::CSomeNumber<1> >
using TTaskB = Meta::CTask<Meta::Bar::MMethod>;
auto taskB = std::make_shared<TTaskB>(std::move(funB));
// Task C
// Write accesses: Bar::anotherString
// Read accesses: none
std::function funC = [&]()
{
std::cout << "Execute function C\n";
sleep_for(sleepDuration);
myBar->SetAnotherString("Test");
sleep_for(sleepDuration);
std::cout << "Function C end\n";
};
// type Meta::CTypeList< struct Meta::Bar::CAnotherString<1> >
using TTaskC = Meta::CTask<Meta::Bar::MSetAnotherString>;
auto taskC = std::make_shared<TTaskC>(std::move(funC));
// Task D
// Write accesses: none
// Read accesses: none
std::function funD = [&]()
{
std::cout << "Execute function D\n";
sleep_for(sleepDurationD);
std::cout << "Function D end\n";
};
// type Meta::CTypeList< struct Meta::CNoResource<0> >
using TTaskD = Meta::CTask<Meta::CNoResources>;
auto taskD = std::make_shared<TTaskD>(std::move(funD));
// Task E
// Write accesses: Foo::number, Bar::someNumber, Bar::anotherString, Bar::someString
// Read accesses: none
std::function funE = [&]()
{
std::cout << "Execute function E\n";
sleep_for(sleepDuration);
myFoo->MethodA(*myBar);
myFoo->MethodB(*myBar);
myFoo->MethodC(*myBar);
sleep_for(sleepDuration);
std::cout << "Function E end\n";
};
// type filtered Meta::CTypeList<struct Meta::Foo::CNumber<1>,struct Meta::Bar::CSomeNumber<1>,struct Meta::Bar::CSomeString<1>,struct Meta::Bar::CAnotherString<1> >
using TTaskE = Meta::CTask<Meta::Foo::MMethodA, Meta::Foo::MMethodB, Meta::Foo::MMethodC>;
auto taskE = std::make_shared<TTaskE>(std::move(funE));
// Add tasks to our task list
// Conflicts:
// - taskA and taskB, because funA wants to read Bar::someString while funB tries to write it
// - taskE has conflicts with taskA, taskB and taskC, with write access to:
// Foo::number, Bar::someNumber, Bar::anotherString, Bar::someString
// - Task D has no conflicts and can run in parallel with all tasks
std::vector<std::shared_ptr<Meta::ITask>> tasks;
tasks.push_back(taskA);
tasks.push_back(taskB);
tasks.push_back(taskC);
tasks.push_back(taskD);
tasks.push_back(taskE);
// One pool is shared across every Execute() call in this process.
// It is owned here in main() and injected into the scheduler by reference
Meta::CMetaThreadPool pool;
// Schedule tasks
// Task A and B execution shall not overlap, since they have a conflicting resource
// Task E has conflicts with A, B and C
// Task D has no conflicts and can run in parallel with all tasks
const std::span<const std::shared_ptr<Meta::ITask>> tasksSpan{tasks};
const Meta::TSchedule schedule = Meta::CScheduler::Schedule(tasksSpan);
// Now execute the schedule
std::cout << "" << std::endl;
std::cout << "Executing tasks:" << std::endl;
Meta::CScheduler::Execute(pool, schedule, tasksSpan, []
{
return true;
});
// Expected if we start with task A:
// 1. start A, C, D
// 2. end A, C
// 3. start B
// 4. end B
// 5. start E
// 6. end E
// 7. end D
/***********************
* Priority demonstration
***********************/
// Pretty-printer for a Meta::TSchedule.
// For each scheduled position it shows the user-visible label of the task running in that slot,
// its priority, and the indices of the slots it has to wait for (its parents in the dependency DAG).
auto printSchedule = [](const char* label,
const Meta::TSchedule& scheduled_tasks,
std::span<const std::shared_ptr<Meta::ITask>> tasks_span,
const std::vector<const char*>& labels)
{
std::cout << '\n' << label << " schedule (priority desc):\n";
// scheduleIdx walks the output order (already topologically sorted,
// because the scheduler emits parents before children by construction).
for (size_t scheduleIdx = 0; scheduleIdx < scheduled_tasks.size(); ++scheduleIdx)
{
// inputIndex maps back to the caller's tasks vector;
// parents are indices into THIS schedule, not the input.
const auto& [taskIndex, parents] = scheduled_tasks[scheduleIdx];
std::cout << " [" << scheduleIdx << "] " << labels[taskIndex]
<< " (prio=" << tasks_span[taskIndex]->GetPriority() << ")"
<< " parents={";
// Comma-separate the parent indices.
for (size_t parent = 0; parent < parents.size(); ++parent)
{
if (parent)
std::cout << ", ";
std::cout << parents[parent];
}
std::cout << "}\n";
}
};
// Sanity print for the original A/B/C/D/E case. All five tasks share the default (lowest) priority,
// so the schedule order matches submission order;
// the interesting part is the parent links derived from the compile-time conflict matrix.
{
std::vector<std::shared_ptr<Meta::ITask>> abcde = {taskA, taskB, taskC, taskD, taskE};
std::vector<const char*> labels = {"A", "B", "C", "D", "E"};
std::span<const std::shared_ptr<Meta::ITask>> view{abcde};
// Build the schedule once and print it;
// the actual execution of this case already happened above through Meta::CTaskScheduler.
const auto sched = Meta::CScheduler::Schedule(view);
printSchedule("A/B/C/D/E", sched, view, labels);
}
// Scenario 1: two tasks with different priorities AND disjoint resources.
// The high-priority task touches Bar::anotherString only;
// the low-priority task touches Bar::someString (read) and Foo::number (write).
// Since the member sets do not overlap, the bitset conflict check returns false
// and neither task accumulates a parent in the schedule. The expected outcome is that both tasks
// launch in parallel even though one is much higher priority;
// priority controls ORDERING in the schedule, not artificial barriers between unrelated tasks.
{
std::cout << "\nScenario 1: non-conflicting low-prio + high-prio -> parents empty\n";
// Low-priority task: simulates a routine read-only synchronisation.
// Annotation Meta::Foo::MReadSomeString -> reads Bar::someString, writes Foo::number.
auto lowPrio = std::make_shared<Meta::CTask<Meta::Foo::MReadSomeString>>(
[]
{
std::cout << "low-prio (read someString) running\n";
},
Meta::EPriority::Low);
// High-priority task: simulates "set another string" -- a write to Bar::anotherString and nothing else.
auto highPrio = std::make_shared<Meta::CTask<Meta::Bar::MSetAnotherString>>(
[]
{
std::cout << "high-prio (write anotherString) running\n";
},
Meta::EPriority::High);
// Pack both tasks into a span the scheduler can read.
// Using a vector of shared_ptr matches what the example app uses elsewhere;
// the scheduler is templated on the pointer type and works just as well with raw ITask*
std::vector<std::shared_ptr<Meta::ITask>> arr = {lowPrio, highPrio};
std::vector<const char*> labels = {"low/readSomeString", "high/writeAnotherString"};
std::span<const std::shared_ptr<Meta::ITask>> view{arr};
// Build the schedule.
// Internally: stable-sort by priority desc (highPrio first because 900 > 100),
// then for each task scan the already-emitted entries for bitset overlap.
// There is none here, so both end up with empty parent lists.
const auto sched = Meta::CScheduler::Schedule(view);
printSchedule("Scenario 1", sched, view, labels);
// Self-check: the whole point of this scenario is
// that the low-prio task does NOT accumulate the high-prio task as a parent.
bool ok = sched.size() == 2
&& sched[0].parents.empty()
&& sched[1].parents.empty();
std::cout << " -> both independent: " << (ok ? "PASS" : "FAIL") << '\n';
// Execute the schedule. With empty parent lists, both worker lambdas skip the parent-wait loop
// and call DoTask() immediately on separate threads. The two "running" lines may print in either order.
Meta::CScheduler::Execute(pool, sched, view, []
{
return true;
});
}
// Scenario 2: two tasks where the resource sets DO overlap on a member (Bar::someString)
// and at least one side writes. The high-priority task writes someString; the low-priority task reads it.
// That's a read-write conflict, so the scheduler must serialise them.
// Because the high-prio task is sorted first, it ends up at schedule index 0 with no parents,
// and the low-prio task ends up at index 1 with parents = {0}. This shows how priority and conflict combine:
// priority breaks the tie about who runs first, conflict tells the scheduler that they cannot overlap.
{
std::cout << "\nScenario 2: conflicting low-prio + high-prio -> low waits for high\n";
// Low-priority task: reads Bar::someString (annotation MReadSomeString).
auto lowPrio = std::make_shared<Meta::CTask<Meta::Foo::MReadSomeString>>(
[]
{
std::cout << "low-prio (read someString) running\n";
},
Meta::EPriority::Low);
// High-priority task: writes Bar::someString (annotation MMethod also writes Bar::someNumber,
// but only the someString overlap matters here).
auto highPrio = std::make_shared<Meta::CTask<Meta::Bar::MMethod>>(
[]
{
std::cout << "high-prio (write someString) running\n";
},
Meta::EPriority::High);
// Same wiring as Scenario 1; only the resource overlap differs.
std::vector<std::shared_ptr<Meta::ITask>> arr = {lowPrio, highPrio};
std::vector<const char*> labels = {"low/readSomeString", "high/writeSomeString"};
std::span<const std::shared_ptr<Meta::ITask>> view{arr};
const auto sched = Meta::CScheduler::Schedule(view);
printSchedule("Scenario 2", sched, view, labels);
// Self-check: high must land at output index 0 (it was sorted first by priority),
// low at index 1, and low's parent list must contain exactly the high-prio slot (index 0).
// The high-prio slot itself has no parents because nothing was emitted before it.
bool ok = sched.size() == 2
&& sched[0].inputIndex == 1
&& sched[0].parents.empty()
&& sched[1].inputIndex == 0
&& sched[1].parents.size() == 1
&& sched[1].parents[0] == 0;
std::cout << " -> high-first, low parent={high}: " << (ok ? "PASS" : "FAIL") << '\n';
// Execute. The low-prio worker waits on the high-prio future before calling DoTask(),
// so the two "running" lines appear in fixed order: high first, then low.
Meta::CScheduler::Execute(pool, sched, view, []
{
return true;
});
}
return 0;
}