According to the C++17 standard, what is the output of this program?
#include <iostream>
#include <string>
#include <future>
int main() {
std::string x = "x";
std::async(std::launch::async, [&x]() {
x = "y";
});
std::async(std::launch::async, [&x]() {
x = "z";
});
std::cout << x;
}
The program is guaranteed to output: z?
C++ reference explicitly mentions the behavior of this code:
If the
std::futureobtained fromstd::asyncis not moved from or bound to a reference, the destructor of thestd::futurewill block at the end of the full expression until the asynchronous operation completes, essentially making code such as the following synchronous:
std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f() std::async(std::launch::async, []{ g(); }); // does not start until f() completes
So your code is guaranteed to print z - there are no data races.
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