Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ 11 thread automatically destroy after detach

Normally, I would assume that C++ 11 thread automatically destroy after detach. But the thing is, I can't find anything to prove this assumption.

According to this article

Once detached, the thread should live that way forever.

forever? If the function of the thread finish, Does its resource remain forever?

According to this article

After a call to this function, the thread object becomes non-joinable and can be destroyed safely.

It can be destroyed safely, but is it automatically?

If it's not destroyed automatically, how to destroy it (not forcefully, but after the function of the thread end)

Thanks for reading.

like image 224
123iamking Avatar asked Aug 15 '17 01:08

123iamking


1 Answers

You should consult a better reference. From std::thread::detach:

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.

So to answer your questions (if they aren't already):

forever?

No. If the thread finishes (for example: if it counts to 10), it is done and it is not running anymore.

Does its resource remain forever?

No, when the thread finishes, every resource from the thread is freed (like variables and such).

It can be destroyed safely, but is it automatically?

What do you mean? When the thread is done, it is destroyed (automatically), regardless of whether you call detach or not. The only difference is that here, they are referring to the thread object, so the actual std::thread instance.

So when the thread object is destructed, you must have called join or detach regardless whether you own that the actual thread finished or not. If you don't, std::terminate is called.

like image 174
Rakete1111 Avatar answered Nov 09 '22 19:11

Rakete1111