Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用异步启动线程并超出其未来的范围是否安全?_C++_Multithreading - Fatal编程技术网

C++ 使用异步启动线程并超出其未来的范围是否安全?

C++ 使用异步启动线程并超出其未来的范围是否安全?,c++,multithreading,C++,Multithreading,我有一个函数需要做一些即时工作(重新分配),然后是一些后台工作(移动旧数据),我可以这样做吗 auto fof = std::async(std::launch::async, &cont2::move_data, this, old_data, old_size); 似乎工作正常,但我很怀疑,因为它不允许我在没有保存返回值的情况下正常使用std::async,而是尝试在同一线程上执行任务。如果返回值astd::future超出范围,它的析构函数将停止线程的执行,直到异步操作完成 这意

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

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

似乎工作正常,但我很怀疑,因为它不允许我在没有保存返回值的情况下正常使用std::async,而是尝试在同一线程上执行任务。

如果返回值a
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

请参阅。

请注意,对于
未来的
对象,此行为是异常的。它仅适用于由
async
返回的
future
s。因为上帝禁止C++是有意义的…