I am running Visual Studio 2012 and attempting to learn how std::async works. I have created a very simple C++ console application:
#include "stdafx.h" #include <future> #include <iostream> void foo() { std::cout << "foo() thread sleep" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "foo() thread awake" << std::endl; } int main() { std::future<void> res = std::async(std::launch::async, foo); res.get(); std::cout << "MAIN THREAD" << std::endl; system("pause"); return 0; } My initial expectation was to see "MAIN THREAD" printout appearing before "foo() thread awake" since the two threads are running asynchronously, with the foo() trailing behind due to its sleeping behavior. However, that is not what is actually happening. The call to res.get() blocks until foo() wakes up, and only then does it get to the "MAIN THREAD" printout. This is indicative of a synchronous behavior, so I am wondering what if perhaps I am either missing something, or not fully grasping the implementation. I have looked through numerous posts on this matter, but still cannot make any sense of it. Any help would be appreciated!
future::getdoes?get()on astd::future<>instance blocks the thread until you get its result. en.cppreference.com/w/cpp/thread/future/get