I noticed something surprising with std::async.According to http://en.cppreference.com/w/cpp/thread/async"If policy & std::launch::async != 0 (the async bit is set), spawns a new thread of execution as if by std::thread(f, args...), except that if the function f returns a value or throws an exception, it is stored in the shared state accessible through the std::future that async returns to the caller."However in my app using std::async(std::launch::async, ...) does not behave as std::thread(...). In my app I have twenty very expensive network calls that block for 10 seconds. I used to do them one after another, which added up to 200s. I changed to using std::thread(...), and now they all executed at the same time in 10s. I then changed to std::async(std::launch::async, ... ) and now it would take about 50s. As in some calls would only start after others had completed. This was surprising to me. And I wonder if its not a bug. I tried it on both windows 8 and windows 2008 SP2. Behaves the same. So async looks a bit lazy even if you tell it to do std::launch::async. Unfortunately I dont have a toy example to show you but I got this pseudocode:Thanks /Petke <fast code> std::vector<std::thread> threadVec; std::for_each(thingVec.begin(), thingVec.end(), [&](const Thing& thing) { auto thread = std::thread([=]() { try { std::cout << "thread start id: " << std::this_thread::get_id() << std::endl; VeryExpensiveBlockingNetworkCall(thing); std::cout << "thread done id: " << std::this_thread::get_id() << std::endl; } catch(std::exception& exc) { std::cout << "Thread Exception: " << exc.what() << std::endl; } catch(...) { std::cout << "Thread Uknwon Exception: " << std::endl; } }); threadVec.push_back(std::move(thread)); }); std::for_each(threadVec.begin(), threadVec.end(), [&](std::thread& thread) { try { std::cout << "join start" << std::endl; thread.join(); std::cout << "join done" << std::endl; } catch(std::exception& exc) { std::cout << "Async Exception: " << exc.what() << std::endl; } }); </fast code> <slow code> std::vector<std::future<void>> futVec; std::for_each(thingVec.begin(), thingVec.end(), [&](const Thing& thing) { auto fut = std::async(std::launch::async, [=]() { std::cout << "thread start id: " << std::this_thread::get_id() << std::endl; VeryExpensiveBlockingNetworkCall(thing); std::cout << "thread done id: " << std::this_thread::get_id() << std::endl; }); futVec.push_back(std::move(fut)); }); std::for_each(futVec.begin(), futVec.end(), [&](std::future<void>& fut) { try { std::cout << "wait start" << std::endl; fut.wait(); std::cout << "wait done" << std::endl; } catch(std::exception& exc) { std::cout << "Async Exception: " << exc.what() << std::endl; } }); </slow code>
Visual Studio/Team Foundation Server/.NET Framework Tooling version
Steps to reproduce
Product Language
Operating System
Operating System Language
Actual results
Expected results
Please wait...