这是一个创建于 1090 天前的主题,其中的信息可能已经有所发展或是发生改变。
#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;
}
2 条回复 • 2021-11-30 14:53:30 +08:00
|
|
1
ysc3839 2021-11-30 13:31:08 +08:00 via Android
等不到“done” 指的是什么呢?
|
|
|
2
mz02005 2021-11-30 14:53:30 +08:00
@ ysc3839 就是 while(!h.done())这句条件总是成立
|