c++ 11 在局部使用async()创建一个线程,当程序运行出局部区域时,为什么代码会阻塞等待线程执行结束?

  1. 在局部使用async()创建一个线程,当程序退出局部区域时,代码阻塞等待线程执行结束

类似下面的代码:必须等待“hi”输出,才能输出“hello world”

int main()
{
    {
            std::async(std::launch::async, [](){
            sleep(10);
            cout << "hi" << endl;
            return 8;
        });
    }
    std::cout << "Hello, World!" << std::endl;
    cin.ignore();
    return 0;
}

async返回的future析构里面会有等待

N3679: Async() future destructors must wait

[..] Futures returned by async() with async launch policy wait in their destructor for the associated shared state to become ready. This prevents a situation in which the associated thread continues to run, and there is no longer a means to wait for it to complete because the associated future has been destroyed. Without heroic efforts to otherwise wait for completion, such a "run-away" thread can continue to run past the lifetime of the objects on which it depends.