VS2015 std :: async is weird
In the VS2015 code below, I get acefbd
on the first line, which is correct. but in the second test, where I split the individual lines, the output is abcdef
.
Is this the 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);
}
source to share
This has nothing to do with Visual Studio, but what do you do with the objects std::future
it returns std::async
.
When the object is std::future
destroyed, the destructor block , waiting for the future to be ready.
What happens with the first line is that you create three future objects, and at the end of the full expression (after the last one is created), the futures are out of scope and destroyed.
In "2nd test" you create one future, which then must be destroyed before the continuation, then you create another future, which must be destroyed before the continuation, and finally the third future, which, of course, must be destroyed.
If you store 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);
source to share