Skip to content

Commit

Permalink
Fix coroutine continuation handle
Browse files Browse the repository at this point in the history
Using coroutines directly by the user e.g. declaring a function with
drogon::Task<> return type, will have it's continuation set to nullptr.

Returning nullptr causes a segfault and it must be checked before
returning e.g. the snippet form https://en.cppreference.com/w/cpp/coroutine/noop_coroutine

```cpp
struct final_awaiter
{
    std::coroutine_handle<>
        await_suspend(std::coroutine_handle<promise_type> h) noexcept
    {
        // final_awaiter::await_suspend is called when the execution of the
        // current coroutine (referred to by 'h') is about to finish.
        // If the current coroutine was resumed by another coroutine via
        // co_await get_task(), a handle to that coroutine has been stored
        // as h.promise().previous. In that case, return the handle to resume
        // the previous coroutine.
        // Otherwise, return noop_coroutine(), whose resumption does nothing.

        if (auto previous = h.promise().previous; previous)
            return previous;
        else
            return std::noop_coroutine();
    }
};
```

This commit default initializes the continuation handle to no op coroutine and
avoids the check.

Signed-off-by: Omar Mohamed <[email protected]>
  • Loading branch information
omar-mohamed-khallaf committed Sep 18, 2024
1 parent 1b46535 commit 109bbcc
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/inc/drogon/utils/coroutine.h
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ struct [[nodiscard]] Task

std::optional<T> value;
std::exception_ptr exception_;
std::coroutine_handle<> continuation_;
std::coroutine_handle<> continuation_{std::noop_coroutine()};
};

auto operator co_await() const noexcept
Expand Down Expand Up @@ -332,7 +332,7 @@ struct [[nodiscard]] Task<void>
}

std::exception_ptr exception_;
std::coroutine_handle<> continuation_;
std::coroutine_handle<> continuation_{std::noop_coroutine()};
};

auto operator co_await() const noexcept
Expand Down

0 comments on commit 109bbcc

Please sign in to comment.