c++20 coroutine 的测试,总是等不到“done”,是我哪里理解有问题?

2021-11-30 11:14:18 +08:00
 mz02005
#include <coroutine>
#include <iostream>
#include <thread>
#include <cassert>

struct Awaiter {
typedef std::coroutine_handle<> CoRoutine;

Awaiter() {}
bool await_ready() {
std::cout << "await ready or not" << std::endl;
return false;
}

auto await_resume() {
std::cout << "await resumed" << std::endl;
return 10086;
}

void await_suspend(std::coroutine_handle<> h) {
std::cout << "await suspended" << std::endl;
printf("h=%p\n", &h);
std::thread([h]()
{
for (size_t i = 0; i < 2; i++)
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
putc('.', stdout);
}
puts("R");
h.resume();
}).detach();
}
};

template <class T>
struct Task {
struct promise_type {
auto get_return_object() noexcept {
std::cout << "get return object" << std::endl;
return Task<T>();
}

auto initial_suspend() noexcept {
std::cout << "initial suspend, return never" << std::endl;
return std::suspend_never{};
}

auto final_suspend() noexcept {
std::cout << "final suspend, return never" << std::endl;
return std::suspend_never{};
}

void unhandled_exception() {
std::cout << "unhandle exception" << std::endl;
std::terminate();
}

void return_value(int val) {
std::cout << "return value\n";
}
};
};

template <>
struct Task<void> {
struct promise_type {
auto get_return_object() noexcept {
std::cout << "get return object" << std::endl;
return Task<void>();
}

auto initial_suspend() noexcept {
std::cout << "initial suspend, return never" << std::endl;
return std::suspend_never{};
}

auto final_suspend() noexcept {
std::cout << "final suspend, return never" << std::endl;
return std::suspend_never{};
}

void unhandled_exception() {
std::cout << "unhandle exception" << std::endl;
std::terminate();
}

void return_void() {
std::cout << "return void" << std::endl;
return;
}
};
};

Task<void> CoroutineFunc() {
std::cout << "before co_await" << std::endl;
for (int i = 0; i < 3; i++)
auto xx = co_await Awaiter();
std::cout << "after co_await" << std::endl;
}

int main() {
std::cout << "main() start" << std::endl;
auto co = CoroutineFunc();
auto h = std::coroutine_handle<decltype(co)>::from_promise(co);
assert(&h.promise() == &co);
while (!h.done())
{
putc('*', stdout);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
h.destroy();
std::cout << "main() exit" << std::endl;
}
1060 次点击
所在节点    问与答
2 条回复
ysc3839
2021-11-30 13:31:08 +08:00
等不到“done” 指的是什么呢?
mz02005
2021-11-30 14:53:30 +08:00
@ysc3839 就是 while(!h.done())这句条件总是成立

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/818971

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX