13

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?

12
  • 1
    Looks like undefined behavior to me. Is there anything that guarantees the synchronization of those tasks? Jun 5 at 2:04
  • 2
    The behavior of program is undefined and can be "x", "y", "z" depending on the timing and scheduling of the threads. There is a potential for data race and multiple threads may access and modify the same variable concurrently without proper synchronization.
    – Byte Ninja
    Jun 5 at 2:09
  • 8
    A future returned by std::async is special - it always blocks in a destructor, so the output is guaranteed to be z - there are no races here.
    – Evg
    Jun 5 at 2:14
  • 2
    @PeteBecker If the retuned future blocks on destruction the second call to async can't happen until after x has been modified by the first call. Jun 5 at 2:17
  • 2
    @PeteBecker There are no unsequenced modifications of x in this code.
    – Evg
    Jun 5 at 2:18

2 Answers 2

17

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.

6

I don't believe that cppreference is entirely accurate in this case.

The standard says that the dtor for std::future releases any shared state (§[futures.unique_future]/9):

~future();
Effects:

  • Releases any shared state (31.6.5);
  • destroys *this.

The description of releasing the shared state says (§[futures.state]/5):

When an asynchronous return object or an asynchronous provider is said to release its shared state, it means:

  • if the return object or provider holds the last reference to its shared state, the shared state is destroyed; and
  • the return object or provider gives up its reference to its shared state; and
  • these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.

[emphasis added]

Summary

In essence, the code has undefined behavior. While an implementation is allowed generate code to block for the shared state to become ready, it is not required to do so, and is not even required to document whether it will do so or not. As such, what you have is pretty much the typical situation for undefined behavior: you may get what you expect, but it isn't required.

Reference

I quoted from N4713, which (if memory serves) is pretty much the C++17 standard. It looks like the wording remains the same up through at least N4950 (which is pretty much C++23.).

11
  • Mmmmhhh, so even adding the [[nosdiscard]] to std::async is a guarantee for "correct" behavior then. From practical experience: returning from std::async doesn't mean Function has been even called yet, and this CAN be a noticable race condition. And yes there are places in my code where I actually do have to synchronize (check Function has started) on the line after calling std::async. Jun 5 at 5:21
  • 4
    [futures.async]/5.4 is the normative wording that requires blocking.
    – T.C.
    Jun 5 at 5:49
  • @T.C.: I may have to reread that when I'm not tired. Right now I'm not seeing how it requires the synchronization that's necessary for this case. Jun 5 at 6:31
  • 2
    @JerryCoffin In English: "synchronizes with" meaning, in practice, blocking. std::async is special because ~future() (releasing the shared state) blocks until thread completion.
    – Passer By
    Jun 5 at 7:25
  • 1
    @JerryCoffin We're not writing to a std::string. "Writing" and "reading" are not defined for objects of class type. You can only read or write objects of scalar type. The assignments in the lambdas are not "writes"; they are calls to std::string::operator=, which does a whole lot of reads and writes to the scalar subobjects of its receiver (and maybe others on the heap). These operations are all observable side effects, they can be synchronized, and the OP's code has the expected behavior. (The standard isn't going to make synchronization with objects impossible!)
    – HTNW
    Jun 5 at 18:40

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.