2013-04-30 4 views
19

반환 된 미래의 소멸자가 차단되기 때문에 아래에 차단되는 async 전화 :비동기를 차단하는 방법?

void foo() {} 

void foo_async() { 
    std::async(std::launch::async, foo); 
} 

하지만 차단 싶지 않아! 이 괜찮

void foo_async() { 
    std::thread(foo).detach(); 
} 

:

나는 다음과 같은 해결 방법을 사용하여 고려 중이 야? 아니면 다른 솔루션을 추천 하시겠습니까?

+3

작업에서 값을 반환하거나 완료 될 때까지 기다릴 필요가 없다면 나에게 합리적인 것처럼 보입니다. – jcoder

답변

10

non-blocking future를 제공하는 async의 다음 버전을 사용할 수 있습니다. 따라서 미래가 필요할 때 활용할 수 있으며, 반대편에서는 화재와 잊기 작업을 원할 때 무시할 수 있습니다.

template< class Function, class... Args> 
std::future<typename std::result_of<Function(Args...)>::type> async(Function&& f, Args&&... args) 
{ 
    typedef typename std::result_of<Function(Args...)>::type R; 
    auto bound_task = std::bind(std::forward<Function>(f), std::forward<Args>(args)...); 
    std::packaged_task<R()> task(std::move(bound_task)); 
    auto ret = task.get_future(); 
    std::thread t(std::move(task)); 
    t.detach(); 
    return ret; 
} 
+0

이것이 왜 비 차단인지 설명 할 수 있습니까? 나에게 그것은 미래의 소멸자가 호출되면 여전히 상대방을 차단하는 것처럼 보인다. – thejinx0r

+0

패키지 된 작업의 @thejinx0r 향후 소멸자가 차단되지 않습니다. – inf

4

foo() 번으로 전화를 걸고 싶다면 해결 방법이 좋다고 말할 수 있습니다.

그렇지 않으면 auto f = std::async(std::launch::async, foo);으로하고 아마도 foo_async()에서 미래를 돌려 보내십시오.

+1

예외가'foo'에서 빠져 나오면 붐. –