29auto computeClosure(std::set<T> startElts, std::set<T> & res, GetEdgesAsync<T> getEdges, CompletionToken token)
31 auto initiator = [&res, startElts = std::move(startElts), getEdges = std::move(getEdges)](
auto handler) {
32 auto executor = asio::make_strand(asio::get_associated_executor(handler));
34 using Executor =
decltype(executor);
35 using Handler =
decltype(handler);
40 struct State : std::enable_shared_from_this<State>
43 GetEdgesAsync<T> getEdges;
50 asio::executor_work_guard<
decltype(State::executor)> workGuard;
51 std::size_t pending = 0;
55 std::size_t inFlight = 0;
59 std::size_t maxConcurrent = 1024;
68 std::exception_ptr error;
70 State(Executor executor_, GetEdgesAsync<T> getEdges, Handler handler, std::set<T> & res)
72 , getEdges(std::move(getEdges))
73 , handler(std::move(handler))
75 , workGuard(asio::make_work_guard(executor_))
79 void complete(std::exception_ptr ex)
82 asio::post(executor, [state = this->shared_from_this(), ex] { state->handler(ex); });
85 void fail(std::exception_ptr ex)
91 void enqueue(
const std::set<T> & elts)
93 for (
const auto & elt : elts)
97 void spawnWorker(
const T & elt)
100 asio::post(executor, [state = this->shared_from_this(), elt] {
103 [state, elt]() -> asio::awaitable<void> {
105 state->enqueue(co_await state->getEdges(elt));
107 state->fail(std::current_exception());
120 if (!todo.empty() && !error) {
121 auto next = std::move(todo.front());
123 asio::post(executor, [state = this->shared_from_this(), next = std::move(next)]()
mutable {
124 state->spawnWorker(next);
129 pending -= todo.size();
138 void enqueue(
const T & elt)
143 if (!res.insert(elt).second)
148 if (inFlight < maxConcurrent) {
156 auto state = make_ref<State>(executor, std::move(getEdges), std::move(handler), res);
157 if (startElts.empty()) {
159 state->complete(std::exception_ptr{});
163 asio::post(executor, [state, startElts = std::move(startElts)] { state->enqueue(startElts); });
166 return asio::async_initiate<CompletionToken, void(std::exception_ptr)>(std::move(initiator), token);