分离线程然后让它超出范围(并使其仍在运行)是否安全?

cod*_*der 9 c++ detach stdthread

我有以下代码,我认为它可以正常工作(请原谅愚蠢/人为的例子)。

void run_thread()
{
    std::thread t([]{
        while(true)
        {
            // keep getting chars... to stop peoples eye's hurting : )
            char c = getchar();
        }
    });

    t.detach(); // Detach thread

    // thread goes out of scope here - but is it ok because its detached??
}

int main()
{
     run_thread();    

    // Wait here forever
    while (true) {;}
}
Run Code Online (Sandbox Code Playgroud)

但在重读之后,我对它产生了怀疑。线程 t 超出范围。我现在不记得在你调用 detach() 之后这样做是否安全......我想是的,但正如我所说,我有一个唠叨的疑问。任何人都可以确认这是否是好的/坏的做法?

Gau*_*gal 7

线程 t 超出范围。我现在不记得在你调用 detach() 之后这样做是否安全

detach()因为要撇清实际运行的线程与线程对象。所以 after} t超出范围但实际线程将继续运行,直到其指令完成。

如果不是因为detach() std::terminate会在以下位置杀死线程}