I am running a series of coroutines with asio :: spawn, and I want to wait until they all finish, and then do another job. How can I do that?
The control flow is as follows:
asio::spawn (io, [] (asio::yield_context yield) { ... // starting few coroutines asio::spawn (yield, [] (asio::yield_context yield2) { ... }); asio::spawn (yield, [] (asio::yield_context yield2) { ... }); asio::spawn (yield, [] (asio::yield_context yield2) { ... }); asio::spawn (yield, [] (asio::yield_context yield2) { ... }); // now I want to wait for all of them to finish before I do // some other work? ... }); io.run ();
UPDATE
Below is a sample code
#include <boost/asio.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/steady_timer.hpp> #include <chrono> #include <iostream> using namespace std; int main () { using namespace boost::asio; io_service io; spawn (io, [&] (yield_context yield) { cout << "main coro starts\n"; auto lambda = [&] (yield_context yield) { cout << "in lambda inside subcoroutine - starts\n"; steady_timer t (io, std::chrono::seconds (1)); t.async_wait (yield); cout << "in lambda inside subcoroutine - finishes\n"; }; // starting few coroutines spawn (yield, lambda); spawn (yield, lambda); // now I want to wait for all of them to finish before I do // some other work? // ??? cout << "main coro finishes\n"; }); io.run (); }
And the result:
// main coro starts // in lambda inside subcoroutine - starts // in lambda inside subcoroutine - starts // main coro finishes <---- // in lambda inside subcoroutine - finishes // in lambda inside subcoroutine - finishes
While I expect:
// main coro starts // in lambda inside subcoroutine - starts // in lambda inside subcoroutine - starts // in lambda inside subcoroutine - finishes // in lambda inside subcoroutine - finishes // main coro finishes
(see the location of the line "main coro finishes")
source share