std::thread finishes before I can detach it

廉价感情. 提交于 2019-12-11 01:44:54

问题


If I create an std::thread that terminates before I am able to call detatch() on it, what is the expected behavior? Should an exception be thrown due to the fact that joinable is already false?

If this is so, then is there a way to create a thread which is initialized into a detached state so that I can avoid this error?

Example:

void func()
{
    // do something very trivial so that it finishes fast
    int a = 1;
}

void main()
{
    thread trivial(func);
    trivial.detach();
}

I realize that it isn't really practical to spawn a thread to do trivial work in practice, however I did manage to run into this behavior, and I was curious to know if there is a way around it...


回答1:


Join and detach have the same requirement, they have to be joinable. So I think doing the joinable check should suffice.

If(trivial.joinable())
    trivial.detach();

The documentation states:

A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

So my guess would be that the detached thread will cease to exist right away. But it definitily can be created.

Note: It's good practice to always call joinable() before joining or detaching a thread.




回答2:


The thread object will be destructed when its scope will be done. To make sure that object finished its job you need either call join or detach.



来源:https://stackoverflow.com/questions/27394123/stdthread-finishes-before-i-can-detach-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!