From 0da22e777dea985d42d055e42515b16b8d5d57ea Mon Sep 17 00:00:00 2001 From: q66 Date: Fri, 17 Mar 2017 03:04:15 +0100 Subject: [PATCH] add a way to retrieve the current coroutine context --- ostd/internal/context.hh | 17 +++++++++++++++-- src/context_stack.cc | 6 ++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/ostd/internal/context.hh b/ostd/internal/context.hh index d081cd1..398030b 100644 --- a/ostd/internal/context.hh +++ b/ostd/internal/context.hh @@ -15,8 +15,10 @@ #include "ostd/context_stack.hh" namespace ostd { -namespace detail { +struct coroutine_context; + +namespace detail { /* from boost.fcontext */ using fcontext_t = void *; @@ -40,12 +42,19 @@ namespace detail { fcontext_t const to, void *vp, transfer_t (*fn)(transfer_t) ); + OSTD_EXPORT extern thread_local coroutine_context *coro_current; } /* namespace detail */ struct coroutine_context { + static coroutine_context *current() { + return detail::coro_current; + } + protected: coroutine_context() {} - ~coroutine_context() { + + /* coroutine context must be polymorphic */ + virtual ~coroutine_context() { unwind(); } @@ -67,7 +76,11 @@ protected: void call() { p_state = state::EXEC; + /* switch to new coroutine */ + coroutine_context *curr = std::exchange(detail::coro_current, this); coro_jump(); + /* switch back to previous */ + detail::coro_current = curr; if (p_except) { std::rethrow_exception(std::move(p_except)); } diff --git a/src/context_stack.cc b/src/context_stack.cc index b4f4bf4..b26f41c 100644 --- a/src/context_stack.cc +++ b/src/context_stack.cc @@ -158,4 +158,10 @@ size_t stack_traits::default_size() noexcept { #endif } +struct coroutine_context; + +namespace detail { + OSTD_EXPORT thread_local coroutine_context *coro_current = nullptr; +} + } /* namespace ostd */