可以std :: Future Cavus Coledump而无需或等待

发布于 2025-02-01 19:17:52 字数 585 浏览 1 评论 0 原文

void func() {
    std::future<int> fut = std::async(std::launch::async, []{
        std::this_thread::sleep_for(std::chrono::seconds(10));
        return 8; 
    });
    return;
}

假设我有这样的功能。 std :: future&lt; int&gt; 的对象 fut 使用 std :: async job初始化,将来会返回整数。但是 fut 将在函数 func 返回之后立即发布。

是否存在这样的问题:当 std :: async 作业返回并尝试将 8 分配给对象 fut ,该对象已经已经存在被释放了...

如果是这样,可能会发生关于Sigsegv的核心...

我对吗?还是 std :: Future 有一些避免此问题的机制?

void func() {
    std::future<int> fut = std::async(std::launch::async, []{
        std::this_thread::sleep_for(std::chrono::seconds(10));
        return 8; 
    });
    return;
}

Let's say that I have such a function. An object fut of std::future<int> is initialized with a std::async job, which will return an integer in the future. But the fut will be immediately released after the function func returns.

Is there such an issue: When the std::async job returns and try to assign the 8 to the object fut, the object has already been released...

If so, a coredump about SIGSEGV may occur...

Am I right about it? Or std::future has some mechanism to avoid this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素罗衫 2025-02-08 19:17:52

std :: async 创建的期货具有阻止驱动器,以等待任务完成。

即使您从 std :: Promise 中创建未来, 〜Future() 不要提及您要问的问题。

文档经常使用“共享状态”一词,这意味着承诺和未来共享一个(堆分配给?)状态,该状态具有返回价值,直到两个人都死亡之前才被摧毁。

Futures created with std::async have a blocking destructor that waits for the task to finish.

Even if you instead create a future from std::promise, the docs for ~future() don't mention the problem you're asking about.

The docs use the term "shared state" a lot, implying that a promise and a future share a (heap-allocated?) state, which holds the return value, and isn't destroyed until both die.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文