[英]is it safe to detach a thread and then let it go out of scope (and have it still running)?
I have the following code, which I think works ok (forgive the silly/contrived example). 我有以下代码,我认为可以正常工作(原谅愚蠢/人为的示例)。
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) {;}
}
But after re-reading it I have a doubt about it. 但是在重新阅读之后,我对此表示怀疑。 Thread t goes out of scope.
线程t超出范围。 I can't remember now if it is safe to do this after you have called detach()... I think it is, but as I say I have a nagging doubt.
我现在不记得在调用detach()之后这样做是否安全了……我认为是,但是正如我所说的那样,我有一个令人困扰的疑问。 Can anyone confirm if this is good/bad practise?
谁能确认这是好事还是坏事?
Thread t goes out of scope.
线程t超出范围。 I can't remember now if it is safe to do this after you have called detach()
我现在不记得在调用detach()之后这样做是否安全
You detach()
because you want to disassociate the actual running thread with the thread object. 之所以使用
detach()
是因为您要取消实际正在运行的线程与线程对象的关联。 So after }
t
goes out of scope but the actual thread will keep on running until its instruction completes. 因此,在
}
t
超出范围后,实际线程将继续运行,直到其指令完成。
If it weren't for detach()
std::terminate
would have killed the thread at }
如果不是
detach()
std::terminate
将会杀死}
的线程
detach
basically releases the std::thread
object instance which is the C++ "handle" to the actual OS thread, thereby making it impossible to join
the thread later. detach
基本上将std::thread
对象实例释放为实际OS线程的C ++“句柄”,从而使以后无法join
该线程。
In most cases it's better to keep the thread
instance around at some global scope so that you can join
it later, for example before exiting main
. 在大多数情况下,最好将
thread
实例保留在某个全局范围内,以便以后可以join
它,例如在退出main
之前。 That way you can ensure all threads finish before the main thread. 这样,您可以确保所有线程在主线程之前完成。
For example: 例如:
std::thread t; // can be "empty"
void run_thread()
{
t = std::thread([]{
while(true)
{
// keep getting chars...
char c = getchar();
}
});
}
int main()
{
run_thread();
// Wait here
std::this_thread::sleep_for(30s);
// Before exiting wait for the thread to finish
if (t.joinable())
t.join();
}
这种用法是分离的地步 。
Yes, it is ok and safe in you code. 是的,在您的代码中可以安全进行。 But it does not have any sense.
但这没有任何意义。
main
function will utilize CPU and a thread function will get less CPU time. main
功能将利用CPU,而线程功能将减少CPU时间。 You can attach to forever thread and reach similar behaviour: run_thread
will never exit, thus main
will never exit. 您可以附加到永久线程并达到类似的行为:
run_thread
将永远不会退出,因此main
永远不会退出。
void run_thread()
{
std::thread t([]{
while(true){/* also run forever */;}
});
// Wait here forever
t.attach();
}
int main()
{
run_thread();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.