使用async结束线程并超出其未来的范围是否安全?

Is it safe to shoot off a thread using async and go out the scope of its future?

本文关键字:范围 范围是 是否 安全 未来 结束 async 线程 使用      更新时间:2023-10-16

我有一个函数,需要做一些即时的工作(重新分配),然后一些后台工作(移动旧数据),我可以这样做吗?

auto fof = std::async(std::launch::async, &cont2::move_data, this, old_data, old_size);

似乎工作得很好,但我很怀疑,因为它不会让我使用std::async通常没有东西来保持返回值,并尝试在同一线程上执行任务。

如果返回值std::future超出作用域,则其析构函数将停止线程的执行,直到异步操作完成。

这意味着,是的,如果你不返回一个结果,它将同步;对std::async的调用将返回一个临时对象,它将立即调用它的析构函数并阻塞,直到工作完成。类似地,如果将它绑定到一个值,它将继续工作,但一旦绑定值到达其作用域的末端,它将暂停。

例如:

{
    // bind to a value
    auto fof = std::async(std::launch_async, 
                          &cont2::move_data, this, old_data, old_size);
    // do work
} // at this point, execution will halt until cont2::move_data finishes

见http://en.cppreference.com/w/cpp/thread/async .