【发布时间】:2018-11-03 10:12:49
【问题描述】:
我有以下代码,我认为可以正常工作(请原谅愚蠢/做作的示例)。
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) {;}
}
但在重读之后,我对它产生了怀疑。线程 t 超出范围。我现在不记得在你调用 detach() 之后这样做是否安全......我认为是的,但正如我所说,我有一个挥之不去的疑问。任何人都可以确认这是好还是坏的做法?
【问题讨论】:
-
@RichardCritten 是的,我确实看到了这个事实,但它说销毁是安全的(虽然没有告诉我它仍然可以运行)。甚至分离说:
Separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits. After calling detach *this no longer owns any thread.但我只是想加倍确定:) -
题外话,但一个字面上永远运行的线程可能会给你带来一些惊喜timsong-cpp.github.io/cppwp/n4659/…
-
@rustyx ...lol 抱歉,好吧,我会的 .. 我知道我应该做一个更好的例子:o