-
Notifications
You must be signed in to change notification settings - Fork 1
/
graphex.hpp
416 lines (368 loc) · 13.2 KB
/
graphex.hpp
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
#pragma once
#ifndef GRAPH_EX_H
#define GRAPH_EX_H
#include <atomic>
#include <functional>
#include <iostream>
#include <list>
#include <mutex>
#include <optional>
#include <queue>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#ifdef USE_BOOST_LOCKLESS_Q
#include "cptl.hpp"
#else
#include "cptl_stl.hpp"
#endif
namespace GE {
#define likely(x) __builtin_expect((x), 1)
#define unlikely(x) __builtin_expect((x), 0)
#define GE_ENFORCE(x, y) \
do \
if (!(x)) \
throw std::logic_error(y); \
while (0)
class BaseNode {
public:
BaseNode(const char* name) noexcept : _name(name) {}
virtual ~BaseNode() noexcept = default;
virtual void execute() = 0;
virtual size_t getPendingCount() const = 0;
virtual void reset() = 0;
const std::string& getName() const { return _name; }
/// _nextNodes contains the child nodes for current node. Those are nodes
/// which are signal upon the completion of the _task in current nnode
std::vector<BaseNode*> _nextNodes;
protected:
std::string _name;
};
class GraphEx;
template <typename TaskCallback, typename... Args>
class Node final : public BaseNode {
friend class GraphEx;
public:
using NodeType = Node<TaskCallback, Args...>;
using ReturnType = std::invoke_result_t<TaskCallback, Args...>;
using ArgsStorage = std::tuple<Args...>;
using ResultStorage =
typename std::conditional_t<!std::is_void_v<ReturnType>,
ReturnType,
int /* placeholder type for void-returning
function */
>;
using SubscribeCallback = std::function<void(
typename std::conditional_t<!std::is_void_v<ReturnType>,
ReturnType,
std::false_type>)>;
using SubscribeNoArgCallback = std::function<void(void)>;
Node(GraphEx* executor, TaskCallback task, const char* name)
: BaseNode(name), _task(task), _executor(executor)
{
}
~Node() noexcept = default;
virtual size_t getPendingCount() const final { return _pendingCount; }
/// @brief setParent add a node as a prequel to current node, and the
/// result of parent node will be passed or consumed by current node once
/// the parent node _task is done
/// @param idx template argument of the position of result object in current
/// node's `_args` For example, let's say there are 3 functions, whose
/// signatures as followed
/// ```
/// a = []() -> int {}
/// b = []() -> int {}
/// c = [](int x, int y) -> int {}
/// ```
/// We need to know whether the result returned by a is passed as `x` or `y`
/// to c. Using `setParent`, we can specify by
/// ```
/// nodeC->setParent<0>(*nodeA) // if result by a is passed as x or
/// nodeC->setParent<1>(*nodeA) // if result by a is passed as y or
/// ```
/// @param parent parent node to be added
template <std::size_t idx, typename ParentTask>
void setParent(ParentTask* parent)
{
static_assert(
!std::is_same_v<typename ParentTask::ReturnType, void>,
"Could not record result of a function that returns void as "
"an argument for this task");
parent->addChild(std::bind(
&Node::onArgumentReady<idx>, this, std::placeholders::_1));
parent->_nextNodes.emplace_back(this);
}
/// @brief setParent add a node as a prequel to current node. The parent
/// won't be passing any result needed by current node, but it still
/// requires the parent node _task to run first before running. For example,
/// ```
/// a = []() -> int {}
/// b = []() -> int {}
/// nodeA->setParent(*nodeB);
/// ```
/// @param parent parent node to be added
template <typename ParentTask>
void setParent(ParentTask* parent)
{
incrementParentCount();
SubscribeNoArgCallback cb = std::bind(
static_cast<void (Node::*)(void)>(&Node::onArgumentReady), this);
parent->addChild(cb);
parent->_nextNodes.emplace_back(this);
}
/// @brief Run the main _task registered by current node
/// After the _task is finish, call the registered callback functions
/// @throw if `ReturnType` is non-copyable but there are more than 1 child
/// tasks that require the result object
virtual void execute() override;
/// @brief Retrieve the result obtained by the current node _task
/// @throw std::runtime_error if No valid result can be retrieved in the
/// node
ReturnType collect()
{
GE_ENFORCE(_result, "No result found in node");
if constexpr (!std::is_copy_constructible<ReturnType>::value) {
GE_ENFORCE(_childTasks.empty(),
"Non copyable result could not be collected: "
"moved to parameters of child tasks");
return std::move(_result.value());
}
else {
return _result.value();
}
}
/// @brief Add a callback function that will be called when the _task in
/// current node finished running. The object generated by the _task in
/// thise node will be passed to or consumed by the callback function
/// `child`
/// @param child callback function
void addChild(SubscribeCallback child)
{
if constexpr (!std::is_copy_constructible<ReturnType>::value) {
GE_ENFORCE(
_childTasks.empty(),
"Non copyable result cannot be passed to more than 1 child "
"process");
}
_childTasks.push_back(child);
}
/// @brief Add a callback function that will be called when the _task in
/// current node finished running. No argument will be passed to the
/// callback function
/// @param child callback function
void addChild(SubscribeNoArgCallback child)
{
_noArgChildTasks.push_back(child);
}
virtual void reset() final
{
_result.reset();
_pendingCount = _parentCount;
}
/// @brief manually inject parameter for a single node
/// CAUTION: This function should not be used with parameters who are
/// expected to be transacted within the graph
///
/// For example if we have 2 nodes
/// nodeA: funcA = () -> int a
/// nodeB: funcB = (int a, int b) -> void
/// and nodeB->setParent<0>(nodeA)
/// we cannot manually inject the first parameter for nodeB, since that
/// parameter is expected to come from A. What we could do is to inject the
/// second parameter by nodeB->feed<1>(param) template @param idx order of
/// the param to be injected
/// @param arg arg to be injected
template <size_t idx, typename ParamType>
void feed(ParamType arg)
{
if constexpr (!std::is_copy_constructible<ParamType>::value ||
std::is_move_constructible<ParamType>::value) {
std::get<idx>(_args) = std::move(arg);
}
else
std::get<idx>(_args) = arg;
--_pendingCount;
}
private:
void incrementParentCount()
{
_parentCount++;
_pendingCount++;
}
/// @brief A register function that can be used to register callback when
/// parent nodes have finish running
template <std::size_t idx>
void onArgumentReady(
decltype(std::get<idx>(std::declval<ArgsStorage>())) arg);
void onArgumentReady();
TaskCallback _task;
ArgsStorage _args;
std::optional<ResultStorage> _result;
size_t _parentCount = std::tuple_size<ArgsStorage>::value;
std::atomic<size_t> _pendingCount = std::tuple_size<ArgsStorage>::value;
std::vector<SubscribeCallback> _childTasks;
std::vector<SubscribeNoArgCallback> _noArgChildTasks;
GraphEx* _executor;
};
class GraphEx {
public:
GraphEx(size_t concurrency = 1) noexcept : _pool(concurrency) {}
template <typename ReturnType, typename... Args>
Node<std::function<ReturnType(Args...)>, Args...>* makeNode(
std::function<ReturnType(Args...)> func,
const char* name = "")
{
_nodes.emplace_back(
std::make_unique<Node<std::function<ReturnType(Args...)>, Args...>>(
this, func, name));
return static_cast<Node<std::function<ReturnType(Args...)>, Args...>*>(
_nodes.back().get());
}
template <typename... Args>
Node<std::function<void(Args...)>, Args...>* makeNode(
std::function<void(Args...)> func,
const char* name = "")
{
_nodes.emplace_back(
std::make_unique<Node<std::function<void(Args...)>, Args...>>(
this, func, name));
return static_cast<Node<std::function<void(Args...)>, Args...>*>(
_nodes.back().get());
}
Node<std::function<void()>>* makeNode(std::function<void()> func,
const char* name = "")
{
_nodes.emplace_back(
std::make_unique<Node<std::function<void()>>>(this, func, name));
return static_cast<Node<std::function<void()>>*>(_nodes.back().get());
}
/// @brief check for cycle in the graph
/// assume all the relevant nodes can be checked from input nodes
bool hasCycle()
{
std::unordered_map<BaseNode*, bool> col;
std::function<bool(BaseNode*)> dfs =
[&](BaseNode* currentNode) -> bool {
col[currentNode] = true;
for (auto& nextNode : currentNode->_nextNodes) {
if (likely(!col.count(nextNode))) {
if (dfs(nextNode)) {
return true;
}
}
else if (unlikely(col[nextNode] == true)) {
return true;
}
}
col[currentNode] = false;
return false;
};
for (auto& node : _nodes) {
col.clear();
if (dfs(node.get())) {
return true;
}
}
return false;
}
void reset()
{
for (auto& node : _nodes) {
node->reset();
}
_finishedCount = 0;
}
/// @brief run the graph execution from input nodes
void execute()
{
std::vector<BaseNode*> initialNodes;
for (auto& nodePtr : _nodes)
if (!nodePtr->getPendingCount())
initialNodes.push_back(nodePtr.get());
for (auto* initialNode : initialNodes)
_pool.push(std::bind(&BaseNode::execute, initialNode));
{
std::unique_lock<std::mutex> lock(_mutex);
_cv.wait(lock,
[this]() { return _finishedCount == _nodes.size(); });
}
}
template <typename NodeType>
void executeSingleNode(NodeType* node)
{
_pool.push(std::bind(&NodeType::execute, node));
}
void onSingleNodeCompleted()
{
std::unique_lock<std::mutex> lock(_mutex);
++_finishedCount;
_cv.notify_all();
}
private:
ctpl::thread_pool _pool;
std::list<std::unique_ptr<BaseNode>> _nodes;
size_t _finishedCount = 0;
std::mutex _mutex;
std::condition_variable _cv;
};
template <typename TaskCallback, typename... Args>
template <std::size_t idx>
void Node<TaskCallback, Args...>::onArgumentReady(
decltype(std::get<idx>(std::declval<std::tuple<Args...>>())) arg)
{
if constexpr (!std::is_copy_constructible<decltype(arg)>::value) {
std::get<idx>(_args) = std::move(arg);
}
else
std::get<idx>(_args) = arg;
if (--_pendingCount == 0)
_executor->executeSingleNode(this);
}
template <typename TaskCallback, typename... Args>
void Node<TaskCallback, Args...>::onArgumentReady()
{
if (--_pendingCount == 0)
_executor->executeSingleNode(this);
}
template <typename TaskCallback, typename... Args>
void Node<TaskCallback, Args...>::execute()
{
// wait for result to be ready
// clang-format off
while (_pendingCount > 0);
// clang-format on
if constexpr (std::is_void_v<ReturnType>) {
if constexpr (!std::is_copy_constructible<decltype(_args)>::value) {
std::apply(_task, std::move(_args));
}
else
std::apply(_task, _args);
}
else {
if constexpr (!std::is_copy_constructible<ReturnType>::value) {
GE_ENFORCE(
_childTasks.size() <= 1,
"Internal Error: More than 1 child process for "
"non-copyable object"); // TODO: should just fail brutally here
_result = std::apply(_task, std::move(_args));
if (!_childTasks.empty()) {
_childTasks[0](std::move(_result.value()));
_result.reset();
}
}
else {
_result = std::apply(_task, _args);
for (size_t i = 0; i < _childTasks.size(); ++i) {
_childTasks[i](_result.value());
}
}
}
for (auto childTask : _noArgChildTasks)
childTask();
// Execution completed here
_executor->onSingleNodeCompleted();
}
} // namespace GE
#endif