0
我有一個很難理解爲什麼下面的代碼塊:任務是阻止如果使用未來像
{
std::async(std::launch::async, [] { std::this_thread::sleep_for(5s);
// this line will not execute until above task finishes?
}
我懷疑std::async
回報std::future
臨時這在析構函數的加入任務線程。可能嗎?
的完整代碼如下:
int main() {
using namespace std::literals;
{
auto fut1 = std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); std::cout << "work done 1!\n"; });
// here fut1 in its destructor will force a join on a thread associated with above task.
}
std::cout << "Work done - implicit join on fut1 associated thread just ended\n\n";
std::cout << "Test 2 start" << std::endl;
{
std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); std::cout << "work done 2!" << std::endl; });
// no future so it should not join - but - it does join somehow.
}
std::cout << "This shold show before work done 2!?" << std::endl;
}
你是對的,'std :: future'的析構函數一直等到它完成時,如果它是等待共享狀態的最後將來,並且它是由'std :: async'創建的。見[這裏](http://en.cppreference.com/w/cpp/thread/future/~future) – Corristo
@Corristo:請在答案部分**中填寫您的答案。 –
@BoundaryImposition由於我沒有包括解決問題的方法,我不認爲它值得回答。 – Corristo