首页 > 解决方案 > C++20 协程,await_resume 返回左值,分段错误

问题描述

正在发生

我只想将数据存储到promise_type,并在协程中获取它。我尝试从 .return 返回左值await_resume()。结果是编译成功,但执行过程中出现Segmentation fault

我该如何改进?


环境


代码

主.cpp:

#include <iostream>
#include <coroutine>
#include <memory>

struct task
{
    struct promise_type
    {
        using data_type = std::unique_ptr<int>;

        task get_return_object() noexcept
        {
            return task(std::coroutine_handle<promise_type>::from_promise(*this));
        }
        std::suspend_never initial_suspend() const noexcept { return {}; }
        void unhandled_exception() {}
        std::suspend_always final_suspend() const noexcept { return {}; }

        data_type data; // my data
    };

    void set_data(promise_type::data_type&& data) // [2] set my data
    {
        handle.promise().data = std::forward<promise_type::data_type>(data);
    }

    void resume()
    {
        handle.resume();
    }

    task(std::coroutine_handle<promise_type> handle) : handle(handle) {}

private:
    std::coroutine_handle<promise_type> handle;
};

struct awaitalbe
{
    bool await_ready() { return true; }
    void await_suspend(std::coroutine_handle<task::promise_type> handle) { this->handle = handle; }
    task::promise_type::data_type&& await_resume()
    {
        return std::move(handle.promise().data); // [3] get my data
    }

    std::coroutine_handle<task::promise_type> handle;
};

task f()
{
    auto p2 = co_await awaitalbe{}; // [4] Segmentation fault here. after [3]
    std::cout << (*p2) << std::endl;
}

int main(int argc, char* argv[])
{
    auto task1 = f();

    task::promise_type::data_type p1 = std::make_unique<task::promise_type::data_type::element_type>(10);
    task1.set_data(std::move(p1)); // [1] set my data

    task1.resume();
    return 0;
}

标签: c++c++20c++-coroutine

解决方案


在您的struct awaitable中,您有:

bool await_ready() { return true; }

澄清一下,await_ready是一种用于确定对应于可等待的结果是否就绪的机制。如果它准备好了,那么就没有充分的理由暂停调用协程(即等待的协程co_await)并等待结果 - 只需调用await_resume检索结果即可。

它允许您执行以下操作:

bool await_ready() {
  if (will_read_block()) {
     return false;
  }
  read_some_data_from_file();
  return true;
}

这样非阻塞读取将同步完成。

在你的情况下,你总是返回 true。这告诉运行时:当协程等待 时awaitable,永远不要挂起该协程并直接调用await_resumeawait_suspend完全跳过挂起。事实上,如果你在 in 中设置断点await_suspend(或者如果你的调试器不喜欢协程,则使用 print 语句)await_suspend,你会发现它永远不会被调用。因此,您实际上从未为结构中的handle成员分配任何内容awaitable,当您尝试从中获得承诺时会导致未定义的行为。

解决方案:只需falseawait_ready.


推荐阅读