Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS2015 std::async strange

In the below code in VS2015, I'm getting acefbd in the first line, which is correct. but in the 2nd test where I seperate out into individual lines, the output is abcdef.

Is that intended behavior?

#include <future>
#include <iostream>

using namespace std;

void a () {
std::cout << "a";
std::this_thread::sleep_for (std::chrono::seconds (3));
std::cout << "b";
}

void c () {
std::cout << "c";
std::this_thread::sleep_for (std::chrono::seconds (4));
std::cout << "d";
}

void e () {
std::cout << "e";
std::this_thread::sleep_for (std::chrono::seconds (2));
std::cout << "f";
}

int main () 
{
    std::async (std::launch::async, a), std::async (std::launch::async, c),  std::async (std::launch::async, e);

cout << "\n2nd Test" << endl;

std::async (std::launch::async, a);
std::async (std::launch::async, c);
std::async (std::launch::async, e);

}
like image 553
Robin Avatar asked Jun 25 '26 02:06

Robin


1 Answers

This has nothing to do with Visual Studio, but what you're doing with the std::future objects that std::async returns.

When a std::future object is destructed, the destructor blocks while waiting for the future to become ready.

What happens with the first line is that you create three future objects, and at the end of the full expression (after you create the last one) the futures go out of scope and are destructed.

In the "2nd Test" you create one future which then has to be destructed before continuing, then you create another future which has to be destructed before continuing, and lastly a third future which of course also has to be destructed.

If you save the futures in the second test in temporary variables, you should get the same behavior:

auto temp_a = std::async (std::launch::async, a);
auto temp_c = std::async (std::launch::async, c);
auto temp_e = std::async (std::launch::async, e);
like image 81
Some programmer dude Avatar answered Jun 27 '26 15:06

Some programmer dude



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!