MSVC 2013 std :: async异步工作,没有wait()

时间:2017-04-25 01:32:31

标签: c++ multithreading future

这是我的代码片段,用于测试是否可以在MSVC2013上异步启动std :: async。结果似乎验证了(没有双关语),但async()阻塞了wait()。现在我很困惑,在std :: async同步(阻塞)性质的论坛上讨论了这么多查询。   使用auto f = async(launch :: async,[] {});代码仍然处于异步模式,但是使用f.get()它会变为同步。    我在这做错了什么? std :: async是否像std :: thread一样具有创建开销? thread_pool是所有这些的唯一答案吗?

   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 . . .

0 个答案:

没有答案
相关问题