Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling std::async twice without storing the returned std::future

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?

like image 284
Yasuo Avatar asked Feb 21 '26 07:02

Yasuo


1 Answers

C++ reference explicitly mentions the behavior of this code:

If the std::future obtained from std::async is not moved from or bound to a reference, the destructor of the std::future will 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.

like image 55
Evg Avatar answered Feb 23 '26 21:02

Evg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!