From 964ac8b0e88fb5789b87e33273e42363958d0afb Mon Sep 17 00:00:00 2001 From: eldritch horrors Date: Sat, 27 Apr 2024 01:02:22 +0200 Subject: libutil: de-callback-ify computeClosure only two users of this function exist. only one used it in a way that even bears resemblance to asynchronicity, and even that one didn't do it right. fully async and parallel computation would have only worked if any getEdgesAsync never calls the continuation it receives itself, only from more derived callbacks running on other threads. calling it directly would cause the decoupling promise to be awaited immediately *on the original thread*, completely negating all nice async effects. Change-Id: I0aa640950cf327533a32dee410105efdabb448df --- src/libutil/closure.hh | 68 +++++++++++--------------------------------------- 1 file changed, 14 insertions(+), 54 deletions(-) (limited to 'src/libutil/closure.hh') diff --git a/src/libutil/closure.hh b/src/libutil/closure.hh index 16e3b93e4..146931fc8 100644 --- a/src/libutil/closure.hh +++ b/src/libutil/closure.hh @@ -1,72 +1,32 @@ #pragma once ///@file +#include #include -#include -#include "sync.hh" - -using std::set; namespace nix { template -using GetEdgesAsync = std::function> &)>)>; - -template -void computeClosure( - const set startElts, - set & res, - GetEdgesAsync getEdgesAsync +std::set computeClosure( + std::set startElts, + std::function(const T &)> getEdges ) { - struct State - { - size_t pending; - set & res; - std::exception_ptr exc; - }; - - Sync state_(State{0, res, 0}); + std::set res, queue = std::move(startElts); - std::function enqueue; + while (!queue.empty()) { + std::set next; - std::condition_variable done; - - enqueue = [&](const T & current) -> void { - { - auto state(state_.lock()); - if (state->exc) return; - if (!state->res.insert(current).second) return; - state->pending++; + for (auto & e : queue) { + if (res.insert(e).second) { + next.merge(getEdges(e)); + } } - getEdgesAsync(current, [&](std::promise> & prom) { - try { - auto children = prom.get_future().get(); - for (auto & child : children) - enqueue(child); - { - auto state(state_.lock()); - assert(state->pending); - if (!--state->pending) done.notify_one(); - } - } catch (...) { - auto state(state_.lock()); - if (!state->exc) state->exc = std::current_exception(); - assert(state->pending); - if (!--state->pending) done.notify_one(); - }; - }); - }; - - for (auto & startElt : startElts) - enqueue(startElt); - - { - auto state(state_.lock()); - while (state->pending) state.wait(done); - if (state->exc) std::rethrow_exception(state->exc); + queue = std::move(next); } + + return res; } } -- cgit v1.2.3