MSVC 2013 std::async works asynchronously without wait()

馋奶兔 提交于 2019-12-12 04:32:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!