考虑以下代码:
#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
是否正确。
set_value
,这是否会导致promise_already_satisfied
的std::future_error
? - dfribmain
和thr_func
在不同的线程中运行。 - LWimsey