"co_yield"是否可以在恢复协程时从调用方返回值?
Can `co_yield` return a value from the caller on resumption of the coroutine?
C++20 引入了协程,可用于创建生成器和其他类似的东西:
generator<int> counter(int max) {
for(int i = 0; i < max; i++) {
co_yield i;
}
}
有没有办法创建一个协程,以便调用方可以提供在协程恢复后由co_yield
返回的响应?我们称之为channel
而不是生成器。
这是我希望能够做的事情的一个例子:
channel<int, int> accumulator(int initial) {
while(true) {
// Can channel be written so co_yield provides a response?
int response = co_yield initial;
initial += response;
}
}
在这里,每当调用方恢复协程时,它都会提供一个值,一旦协程恢复,该值就会从co_yield
返回,如下所示:
std::vector<int> accumulate(std::vector<int> values) {
channel<int, int> acc = accumulator(0);
std::vector<int> summed_values;
for(int v : values) {
// Get whatever value was yielded by the accumulator
int sum = acc.recieve();
// Do something with the value
summed_values.push_back(sum);
// Resume the accumulator, returning this value from co_yield:
acc.send(v);
}
return summed_values;
}
根据评论进行编辑
任何人都可以提供一些关于如何做到这一点的指导或示例吗?协程对我来说仍然很新。我有一个channel
类的基本实现,但我不确定应该从yield_value
返回什么才能实现这一点。
我在评论中标记了(A)
和(B)
的两个位置。
template <class Out, class In>
struct channel {
struct promise_type {
Out current_value;
auto yield_value(Out value) {
current_value = value;
// (A) What do I return here?
}
channel get_return_object() {
return {std::coroutine_handle<promise_type>::from_promise(*this)};
}
// We run up until the first value is ready
auto initial_suspend() noexcept { return std::suspend_never(); }
auto final_suspend() noexcept { return std::suspend_always(); }
void unhandled_exception() noexcept { std::terminate(); }
};
Out receive() {
return handle.promise().current_value;
}
void send(In response) {
// (B) What do I do here?
}
// Constructors, destructor and move assignment operator omitted for brevity
private:
std::coroutine_handle<promise_type> handle = nullptr;
};
密钥是await_resume
,在等待者(yield_value
的结果(上调用它来获取co_yield
的结果。
您还需要将响应存储在某个位置。正如 Raymond Chen 在评论中建议的那样,您可以将值放入promise_type
的新数据成员中。
所以变化是:
-
将数据成员添加到
promise_type
。In response;
-
定义自定义等待程序以返回该数据成员。
struct awaiter : std::suspend_always { friend promise_type; constexpr In await_resume() const { return m_p->response; } private: constexpr awaiter(promise_type* p) : m_p(p) {} promise_type* m_p; };
-
在
(A)
中,返回自定义的等待者。return awaiter(this);
-
在
(B)
中,设置数据成员,然后恢复协程。handle.promise().response = response; handle.resume();
相关文章:
- 在挂钩启动新线程时解除挂钩进程
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 是否有必要获取锁并在不需要唤醒线程时通知condition_variable?
- "co_yield"是否可以在恢复协程时从调用方返回值?
- 线程时访问静态映射时出现隔离错误
- 连接线程时的无限循环
- 视频在唤醒其他线程时输入设备断开连接
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 在 C++ 的 Qt 中使用 WINAPI 线程时出现问题
- 停止 winapi 线程时出现错误行为
- 使用提升线程时编译失败
- C++如何判断互斥体在阻塞其他线程时是否被单个线程不成比例地占用
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 为同一向量C++运行多个线程时出现分段错误
- 调用子例程时类型不匹配
- C++ 线程时出错,标准::调用:
- SetWindowsHookEx 在挂接到其他线程时返回 NULL
- 在PHP扩展中使用emalloc从线程时出现隔离错误
- 尝试在我的基类中启动线程时,Visual Studio 由于调试错误而中止我的程序
- C 多线程,在并行多个线程时获得SegFault