gpt4 book ai didi

c++ - 恢复 final_suspend 会导致错误,不会破坏协程

转载 作者:行者123 更新时间:2023-11-30 03:36:06 25 4
gpt4 key购买 nike

James McNellis 在他的演讲“C++ 协程简介”(https://youtu.be/ZTqHjjm86Bw?t=1898) 中说了以下内容:

协程在以下情况下被销毁:

  • final_suspend 恢复,
  • coroutine_handle<>::destroy() 被调用,

以先发生者为准。

在我的测试中,我看到(VS 2015、VS 2017 RC),恢复在 final_suspend 上暂停的协程会导致错误:

Unhandled exception at 0x010B9EDD in Awaits2017.exe: RangeChecks instrumentation code detected an out of range array access. occurred

知道这里会发生什么吗?

#include <experimental/resumable>

using namespace std;
using namespace std::experimental;

struct Coro
{
coroutine_handle<> m_coro;
Coro(coroutine_handle<> coro) : m_coro(coro) {}

struct promise_type
{
Coro get_return_object()
{
return Coro(coroutine_handle<promise_type>::from_promise(*this));
}

auto initial_suspend() { return false; }
auto final_suspend() { return true; }
void return_void() {}
};
};

Coro simple()
{
co_return;
}

int main()
{
Coro c = simple();
c.m_coro.resume(); // runtime error here
}

最佳答案

经验法则:

  • 如果 final_suspend返回 true , 你应该调用 coroutine_handle<>::destroy() , 而不是 resume() .

  • 如果 final_suspend返回 false , 你不应该调用 destroy()同样,协程将自行清理。

注意VS 2015中包含的coroutine不是James McNellis在视频中展示的(提案有很多修改),描述:

final_suspend is resumed

可能会令人困惑。它并不真正意味着 resume()被称为。

关于c++ - 恢复 final_suspend 会导致错误,不会破坏协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40854347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com