问题
Here is my code snippet to test if std::async indeed can be launched asynchronously on MSVC2013. And the result seems to verify that ( no pun intended), however the async() blocks on wait(). Now I am confused that so many queries on the forum discussed on the std::async synchronous (blocking) nature. With auto f = async(launch::async, [] {}); the code works still in async mode, but with f.get() it becomes sync. What am I doing wrong here? Does std::async have the creation overhead like the std::thread ? Is thread_pool the only answer to all these?
using namespace std;
mutex mu;
void print(string s)
{
lock_guard<mutex> lock(mu);
cout << s << endl;
}
void foo1()
{
async(launch::async, []
{
ostringstream ss; ss << "foo1 " << this_thread::get_id();
print(ss.str() ) ;
this_thread::sleep_for(chrono::seconds(1));
ostringstream ss1; ss1 << "foo1 " << this_thread::get_id() << "
just woke up."; print(ss1.str());
});
async(launch::async, []
{
ostringstream ss; ss << "foo1 " << this_thread::get_id();
print(ss.str());
this_thread::sleep_for(chrono::seconds(1));
ostringstream ss1; ss1 << "foo1 " << this_thread::get_id() << "
just woke up."; print(ss1.str());
});
}
int main()
{
foo1();
this_thread::sleep_for(chrono::seconds(3));
}
The result shows:
foo1 6244
foo1 6240
foo1 6244 just woke up.
foo1 6240 just woke up.
Press any key to continue . . .
来源:https://stackoverflow.com/questions/43600159/msvc-2013-stdasync-works-asynchronously-without-wait