[英]Is this use of std::promise thread safe?
考虑以下代码:
#include <thread>
#include <iostream>
#include <future>
std::promise<int> prom;
void thr_func(int n)
{
prom.set_value(n + 10);
}
int main()
{
std::thread t{thr_func, 5};
auto fut = prom.get_future();
int result = fut.get();
std::cout << result << std::endl;
t.join();
}
可以同时访问prom
对象,即使标准说set_value
是原子的,我也找不到关于get_future
是原子的(或const)的任何信息。
因此,我想知道以这种方式调用get_future
是否正确。
您说对了,该标准并未说明get_future
是原子的。 与set_value
并发调用可能不安全。
相反,请在创建线程之前调用get_future
。 这样可以确保在set_value
之前调用它。
auto fut = prom.get_future();
std::thread t{thr_func, 5};
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.