[英]Is this use of std::promise thread safe?
Consider this code: 考虑以下代码:
#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();
}
The prom
object is accessed concurrently and even though the standard says that set_value
is atomic, I cannot find anything about get_future
being atomic (or const). 可以同时访问
prom
对象,即使标准说set_value
是原子的,我也找不到关于get_future
是原子的(或const)的任何信息。
Therefore I wonder whether it is correct to call get_future
this way. 因此,我想知道以这种方式调用
get_future
是否正确。
You are right that the standard does not say anything about get_future
being atomic. 您说对了,该标准并未说明
get_future
是原子的。 It is probably not safe to call it concurrently with set_value
. 与
set_value
并发调用可能不安全。
Instead, call get_future
before thread creation. 相反,请在创建线程之前调用
get_future
。 That guarantees it is called before set_value
. 这样可以确保在
set_value
之前调用它。
auto fut = prom.get_future();
std::thread t{thr_func, 5};
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.