【问题标题】:Resuming final_suspend causes error, not destroys coroutine恢复 final_suspend 会导致错误,而不是破坏协程
【发布时间】:2016-11-28 22:04:23
【问题描述】:

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

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

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

以先发生者为准。

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

Awaits2017.exe 中 0x010B9EDD 处未处理的异常:RangeChecks 检测代码检测到超出范围的数组访问。发生了

有什么想法吗?

#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
}

【问题讨论】:

  • 在发布的TS initia/final_suspend 不能返回bool。

标签: c++ visual-c++ c++-coroutine


【解决方案1】:

经验法则:

  • 如果final_suspend 返回true,您应该调用coroutine_handle&lt;&gt;::destroy(),而不是resume()

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

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

final_suspend 恢复

可能会令人困惑。这并不意味着调用了resume()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2023-02-12
    • 1970-01-01
    • 2021-08-24
    • 2017-12-23
    相关资源
    最近更新 更多