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...
joinable()
does not depend on whether the thread has finished execution. In your scenario,joinable()
does not in fact becomefalse
until you calldetach()
. There is no problem here in need of a workaround. – DamselfishA thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.
– Snowdrop