c++ - C++20 协程,await_resume 返回左值,分段错误
问题描述
正在发生
我只想将数据存储到promise_type
,并在协程中获取它。我尝试从 .return 返回左值await_resume()
。结果是编译成功,但执行过程中出现Segmentation fault。
我该如何改进?
环境
- 操作系统:WSL2 Ubuntu 20.04
- 编译器:gcc 10.3
- 命令:g++ -std=c++20 -fcoroutines main.cpp
代码
主.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;
}
解决方案
在您的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_resume
,await_suspend
完全跳过挂起。事实上,如果你在 in 中设置断点await_suspend
(或者如果你的调试器不喜欢协程,则使用 print 语句)await_suspend
,你会发现它永远不会被调用。因此,您实际上从未为结构中的handle
成员分配任何内容awaitable
,当您尝试从中获得承诺时会导致未定义的行为。
解决方案:只需false
从await_ready
.
推荐阅读
- angular - 角度等待不等待函数完成
- java - 如何比较 @ElementCollection 和 Spring JPA 中的设置
- android - 从相机捕获图像时,在一加设备中发现 ImageFile 为空
- maven - 如何在这个 pom 中读取这个 google 组件依赖项?
- solr - 在 SOLR 中将突出显示与其余响应合并
- c# - 将推送通知托管到 Android 和 IOS 的离线服务器
- mongodb - 如何在使用 mongo shell 获取匹配的父母时删除子条目
- ios - 如何在 Azure 管道中运行 iOS 移动应用程序的 XCTest(UI 测试用例)?
- vue.js - vue-router 中某些路由的单独导航抽屉
- ruby-on-rails - 如何将变量和纯文本放在Haml表的同一列中