| 1 |
// { dg-skip-if "requires hosted libstdc++ for iostream" { ! hostedlib } } |
| 2 |
#include <iostream> |
| 3 |
#include <exception> |
| 4 |
#include <cassert> |
| 5 |
|
| 6 |
#if __has_include("coroutine") |
| 7 |
#include <coroutine> |
| 8 |
namespace stdcoro = std; |
| 9 |
#else |
| 10 |
#include <experimental/coroutine> |
| 11 |
namespace stdcoro = std::experimental; |
| 12 |
#endif |
| 13 |
|
| 14 |
struct footable : stdcoro::suspend_always { |
| 15 |
footable() noexcept = default; |
| 16 |
~footable() { assert(released); } |
| 17 |
footable(const footable&) = delete; |
| 18 |
|
| 19 |
using coro_handle = stdcoro::coroutine_handle<>; |
| 20 |
|
| 21 |
void await_suspend(coro_handle awaiter) noexcept { |
| 22 |
std::cout << "suspending to footable " << this << std::endl; |
| 23 |
assert(!handle); |
| 24 |
handle = awaiter; |
| 25 |
} |
| 26 |
void await_resume() noexcept { |
| 27 |
std::cout << "resuming from footable " << this << std::endl; |
| 28 |
assert(handle); |
| 29 |
handle = {}; |
| 30 |
} |
| 31 |
|
| 32 |
void operator()() noexcept { |
| 33 |
std::cout << "operator() on " << this << std::endl; |
| 34 |
assert(handle); |
| 35 |
handle.resume(); |
| 36 |
handle = {}; |
| 37 |
} |
| 38 |
|
| 39 |
void release() noexcept { released = true; } |
| 40 |
private: |
| 41 |
coro_handle handle; |
| 42 |
bool released = false; |
| 43 |
}; |
| 44 |
|
| 45 |
struct footask { |
| 46 |
struct promise_type { |
| 47 |
using coro_handle = stdcoro::coroutine_handle<promise_type>; |
| 48 |
|
| 49 |
stdcoro::suspend_never initial_suspend() noexcept { return {}; } |
| 50 |
stdcoro::suspend_never final_suspend() noexcept { std::cout << "final suspend" << std::endl; return {}; } |
| 51 |
void unhandled_exception() {} |
| 52 |
void return_void() noexcept { std::cout << "coro returns" << std::endl; } |
| 53 |
|
| 54 |
footask get_return_object() { return footask{ coro_handle::from_promise(*this) }; } |
| 55 |
}; |
| 56 |
|
| 57 |
footask(promise_type::coro_handle handle) : handle(handle) {} |
| 58 |
~footask() { assert(handle.done()); } |
| 59 |
|
| 60 |
promise_type::coro_handle handle; |
| 61 |
}; |
| 62 |
|
| 63 |
struct bar { |
| 64 |
bar() = default; |
| 65 |
bar(const bar&) = delete; |
| 66 |
|
| 67 |
footable foo{}; |
| 68 |
footask task = taskfun(); |
| 69 |
|
| 70 |
footask taskfun() noexcept { |
| 71 |
std::cout << "coro begin" << std::endl; |
| 72 |
co_await foo; |
| 73 |
std::cout << "coro end" << std::endl; |
| 74 |
} |
| 75 |
}; |
| 76 |
|
| 77 |
int main() { |
| 78 |
bar foobar; |
| 79 |
foobar.foo(); |
| 80 |
assert(foobar.task.handle.done()); |
| 81 |
std::cout << "releasing" << std::endl; |
| 82 |
foobar.foo.release(); |
| 83 |
std::cout << "done" << std::endl; |
| 84 |
return 0; |
| 85 |
} |