59 lines
1.5 KiB
C++
59 lines
1.5 KiB
C++
#include <coroutine>
|
|
#include <iostream>
|
|
#include <stdexcept>
|
|
#include <type_traits>
|
|
|
|
template<class T>
|
|
struct Promise;
|
|
|
|
template<class T>
|
|
struct coroutine: std::coroutine_handle<Promise<T>>{
|
|
using promise_type = ::Promise<T>;
|
|
};
|
|
|
|
template<class T=void>
|
|
struct Promise{
|
|
auto initial_suspend(){
|
|
std::cout<<__FUNCTION__<<'\n';
|
|
return std::suspend_always{};
|
|
// return std::suspend_never{};
|
|
}
|
|
auto final_suspend()noexcept{//最后要不要把句柄执行权限归还,如果不归还,那么协程被销毁,继续检查.done()则Segmentation fault
|
|
std::cout<<__FUNCTION__<<'\n';
|
|
return std::suspend_always{};
|
|
}
|
|
void unhandled_exception(){
|
|
std::cout<<__FUNCTION__<<'\n';
|
|
throw std::runtime_error("unhandled exeception\n");
|
|
}
|
|
void return_value(const std::decay_t<T> &t){
|
|
std::cout<<__FUNCTION__<<' '<<t<<'\n';
|
|
}
|
|
coroutine<T> get_return_object(){
|
|
std::cout<<__FUNCTION__<<'\n';
|
|
return {coroutine<T>::from_promise(*this)};
|
|
}
|
|
auto yield_value(const std::decay_t<T> &t){
|
|
std::cout<<__FUNCTION__<<' '<<t<<'\n';
|
|
return std::suspend_always{};
|
|
}
|
|
|
|
coroutine<T> h;
|
|
};
|
|
|
|
coroutine<int> test(){
|
|
std::cout<<"testing\n";
|
|
co_yield 1;
|
|
co_yield 2;
|
|
co_return 0;
|
|
}
|
|
|
|
int main(){
|
|
std::cout<<__FUNCTION__<<'\n';
|
|
auto handle = test();
|
|
std::cout<<__FUNCTION__<<'\n';
|
|
while (!handle.done()) {
|
|
handle.resume();
|
|
std::cout<<__FUNCTION__<<'\n';
|
|
}
|
|
} |