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).
Therefore I wonder whether it is correct to call get_future
this way.
You are right that the standard does not say anything about get_future
being atomic. It is probably not safe to call it concurrently with set_value
.
Instead, call get_future
before thread creation. That guarantees it is called before set_value
.
auto fut = prom.get_future();
std::thread t{thr_func, 5};
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With