有没有办法取消/分离未来在C ++ 11? [英] Is there a way to cancel/detach a future in C++11?

查看:110
本文介绍了有没有办法取消/分离未来在C ++ 11?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

#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秒,打印Timeout,然后退出。而不是退出,它等待另外9秒,打印睡眠完成,然后segfaults。有没有办法取消或分离未来,所以我的代码将在main结束时退出,而不是等待未来完成执行?

This is supposed to wait 1 second, print "Timeout", and exit. Instead of exiting, it waits an additional 9 seconds, prints "Sleeping Done", and then segfaults. Is there a way to cancel or detach the future so my code will exit at the end of main instead of waiting for the future to finish executing?

推荐答案

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

The C++11 standard does not provide a direct way to cancel a task started with std::async. You will have to implement your own cancellation mechanism, such as passing in an atomic flag variable to the async task which is periodically checked.

你的代码不应该崩溃。在到达 main 的结尾时, std :: future< int> 结果被销毁,这将等待任务完成,然后丢弃结果,清理所使用的任何资源。

Your code should not crash though. On reaching the end of main, the std::future<int> object held in result is destroyed, which will wait for the task to finish, and then discard the result, cleaning up any resources used.

这篇关于有没有办法取消/分离未来在C ++ 11?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆