c++ - Why does boost::when_all spawn a new thread -
i have following code, compiled boost 1.62.
#define boost_thread_version 4 #define boost_thread_provides_executors #include <chrono> #include <thread> #include <boost/thread/future.hpp> #include <boost/thread/executors/loop_executor.hpp> using namespace std::literals::chrono_literals; int main() { auto start = boost::make_ready_future<int>(); boost::loop_executor ex; auto = start.then(ex, [](auto &&) { std::cout << "a"; }).share(); auto b = boost::when_all(a).then(ex, [](auto &&) { std::cout << "b";} ); auto c = boost::when_all(a).then(ex, [](auto &&) { std::cout << "c";} ); auto d = boost::when_all(std::move(b),std::move(c)).then(ex, [](auto &&) { std::cout << "d";} ); while ( ex.try_executing_one() ) std::this_thread::sleep_for(100ms); d.get(); return 0; }
this spawns 4 tasks (a,b,c,d) diamond dependency on them ( b , c depend on a, d depends on b , c ).
given fact using loop_executor
, expected code not spawn thread , output either "abcd" or "acbd".
instead code might or might not deadlock @ d.get()
(just reduce sleep time 0 see deadlocking), because every call when_all
spawns new thread used wait on futures
.
i under impression when_all
implemented in terms of .then
, buffer store task result , atomic counter.
question:
is there fundamental design reason requires when_all
spawn new thread?
in particular wondering if behavior expected hypothetical implementation of concurrency ts.
in opinion, boost::when_all
not spawn new thread, think logic simple follow semantic can understand. boost::loop_executor
spawns threads, , boost::when_all
give threads order. loop_executor
mean execute in loop, if d.get()
happened, deadlock.
Comments
Post a Comment