繁体   English   中英

使用异步触发线程并超越其未来范围是否安全?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM