1. Launch policy 없이 async()를 사용했을 때, std::future::get()(혹은 wait())을 call하지 않으면, 해당 function이 호출된다는 보장이 없다.

#include <future> 

void DoSomething() 
{ 
    // Do something... 
} 

int main() 
{ 
    auto f = std::async([]{ DoSomething(); }); 
    //... 
    f.get(); // Without this, there is no guarantee that DoSomething() will ever be called. 
}

 

2. std::launch::async로 async()를 호출했을 경우는 해당 future object의 destructor가 해당 루틴이 끝날 때까지 block된다. 따라서 async() 자체가 실패하지 않았다면(실패의 경우 std::system_error를 throw) get()이나 wait()를 호출하지 않아도 해당 루틴이 호출됨이 보장된다.

 

3. async()로 여러 루틴을 concurrent하게 launch하려면...

 

  • std::launch::async 사용
  • async()가 리턴하는 future object를 반드시 assign할 것. 그렇지 않으면 단지 sequential call이 될 뿐임.

 

#include <future> 

void foo() 
{ 
    // Do something... 
} 

void bar() 
{ 
    // Do something... 
} 


int main() 
{ 
    try { 
        auto f1 = std::async(std::launch::async, []{ foo(); }); 
        auto f2 = std::async(std::launch::async, []{ bar(); }); 
        //... 
    } 
    catch (std::system_error & ) {
        // Failed to call asynchronously 
    } 
}

'programming > C++' 카테고리의 다른 글

Universal reference  (0) 2013.02.18
shared_ptr, unique_ptr  (0) 2013.02.18
constexpr  (0) 2013.02.18
Uniform initialization in C++11  (0) 2013.02.18
Three Optimization Tips for C++  (0) 2013.02.18
Posted by 무한자전거
,