Created
August 2, 2019 03:28
-
-
Save kghost/f9a8698dc92693b1243649c7b8e473ba to your computer and use it in GitHub Desktop.
coroutine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iterator> | |
#include <iostream> | |
#include <future> | |
#include <experimental/coroutine> | |
std::function<void()> resume; | |
template <typename _Ty, typename _Alloc = std::allocator<char>> | |
class future { | |
public: | |
struct promise_type; | |
using coro_handle = std::experimental::coroutine_handle<promise_type>; | |
struct promise_type { | |
_Ty const *_CurrentValue; | |
auto get_return_object() { return future{}; } | |
auto initial_suspend() { return std::experimental::suspend_never{}; } | |
auto final_suspend() { return std::experimental::suspend_never{}; } | |
void unhandled_exception() { std::terminate(); } | |
auto return_value(_Ty const &_Value) { return std::experimental::suspend_never{}; } | |
}; | |
explicit future() {} | |
~future() {} | |
future(future const &) = delete; | |
future &operator=(future const &) = delete; | |
future(future &&_Right); | |
future &operator=(future &&_Right); | |
bool await_ready() { return completed; } | |
template<typename _Promise> | |
void await_suspend(std::experimental::coroutine_handle<_Promise> && _Coro) { | |
resume = [_Coro = std::move(_Coro)]() mutable { | |
_Coro.resume(); | |
}; | |
} | |
void await_resume() {} | |
private: | |
bool completed; | |
}; | |
future<char> fun_b() { | |
printf("%s:%d\n", __FILE__, __LINE__); | |
co_await std::experimental::suspend_never{}; | |
printf("%s:%d\n", __FILE__, __LINE__); | |
co_await std::experimental::suspend_always{}; | |
printf("%s:%d\n", __FILE__, __LINE__); | |
co_await std::experimental::suspend_always{}; | |
printf("%s:%d\n", __FILE__, __LINE__); | |
co_return 1; | |
} | |
future<int> fun_a() { | |
printf("%s:%d\n", __FILE__, __LINE__); | |
co_await fun_b(); | |
printf("%s:%d\n", __FILE__, __LINE__); | |
co_await fun_b(); | |
printf("%s:%d\n", __FILE__, __LINE__); | |
co_await fun_b(); | |
printf("%s:%d\n", __FILE__, __LINE__); | |
co_return 0; | |
} | |
int main() { | |
auto f = fun_a(); | |
resume(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment