c++ - 有没有办法在 C++11 中取消/分离 future ?

标签 c++ c++11 future

我有以下代码:

#include <iostream>
#include <future>
#include <chrono>
#include <thread>

using namespace std;

int sleep_10s()
{
    this_thread::sleep_for(chrono::seconds(10));
    cout << "Sleeping Done\n";
    return 3;
}

int main()
{
    auto result=async(launch::async, sleep_10s);
    auto status=result.wait_for(chrono::seconds(1));
    if (status==future_status::ready)
        cout << "Success" << result.get() << "\n";
    else
        cout << "Timeout\n";
}

这应该等待 1 秒,打印“超时”,然后退出。它没有退出,而是再等待 9 秒,打印“Sleeping Done”,然后出现段错误。有没有办法取消或分离 future ,所以我的代码将在 main 结束时退出,而不是等待 future 完成执行?

最佳答案

C++11 标准不提供取消以 std::async 开始的任务的直接方法。 .您必须实现自己的取消机制,例如将原子标志变量传递给定期检查的异步任务。

您的代码不应该崩溃。到达 main 结束时, std::future<int> result 中保存的对象被销毁,它将等待任务完成,然后丢弃结果,清理所有使用的资源。

关于c++ - 有没有办法在 C++11 中取消/分离 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12086622/

相关文章:

c++ - 关于虚函数的代价

C++11 统一初始化 : ambiguity between initializer list and multiple-parameter constructors?

multithreading - C++11 - 管理工作线程

c++ - 有人能告诉我为什么这不是常量表达式吗?

scala - Scala 中 Await.result 和 futures.onComplete 的区别

C++ 字符串 - 如何为 wstring 实现这个 'IsEmptyOrSpace(string)' 方法?

c++ - 模板类使用参数包时如何传递其他模板参数?

c++ - 线路运算符(operator)新的段错误

scala - 如何动态生成具有 for-yield 的并行 future

rust - 按顺序执行 future 集合