我有以下代码,我认为它可以正常工作(请原谅这个愚蠢/牵强的例子)。
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()之后是否安全这样做... 我认为是安全的,但是我有一个疑问。 有人可以确认这是否是好/坏习惯吗?
std::thread
析构函数的参考文献可能会很有用。 - Some programmer dude