How to launch a coroutine without blocking current coroutine, and then launch another coroutine and wait for its result? #436
-
|
Let's assume we have two coroutine functions: #include <async_simple/coro/SyncAwait.h>
#include <async_simple/coro/Lazy.h>
#include <async_simple/coro/Sleep.h>
#include <async_simple/executors/SimpleExecutor.h>
using namespace std::chrono_literals;
namespace coro = async_simple::coro;
coro::Lazy<> coro1() {
for(int i = 0; i <= 40; i++){
co_await coro::sleep(1s);
std::println("1");
}
co_return;
}
coro::Lazy<std::string_view> coro2() {
for(int i = 0; i <= 40; i++) {
co_await coro::sleep(1s);
std::println("2");
}
co_return "FINISHED";
}What I want to do is like the code below in JavaScript: async function run() {
// Launch coro1 without blocking
coro1().finally(() => { console.log("coro1 done"); });
// Launch coro2, block until coro2 `co_return`
const coro2Result= await coro2();
console.log(coro2Result);
}I try to write code like this, but it doesn't work as expected coro::Lazy<> run() {
coro1().start([](auto &&_) {});
auto coro2Result = co_await coro2();
std::cout << coro2Result << '\n';
co_return;
}
int main() {
coro::syncAwait(run());
return 0;
}Result: |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
|
After some exploration, it turns out:
|
Beta Was this translation helpful? Give feedback.
-
p.s. |
Beta Was this translation helpful? Give feedback.
-
|
This is bad, we should provide a full-functional, out-of-box executor to users. |
Beta Was this translation helpful? Give feedback.
-
|
It will be better to call |
Beta Was this translation helpful? Give feedback.
By design, the users can and should provide their own executors.