Reputation: 1475
I have a thread like:
std::thread t{ [](){} };
So the new thread finishes suddenly. If I didn't call join
is it possible that the operating system would switch context to this "dead" thread? Or system "noticed" that this thread is not active and never switch to it even if I never call join
?
Upvotes: 1
Views: 1175
Reputation: 6332
The exact algorithm for when the OS might switch to your thread is not defined by C++ but by your OS scheduler.
According to the standard §30.3, if t.joinable()
is true, then there likely exists an operating system thread corresponding to your thread object. Note that t.joinable()
is true even if the thread has run to completion, as long as the thread has not been joined or detached.
If you have detached, the object is no longer connected to the underlying OS thread implementation, which is generally now the responsibility of the OS to cleanup (e.g., at program termination), unless you do something platform dependent like work with the native handle explicitly. After a detach, the code for that thread may still be running.
Upvotes: 0
Reputation: 5304
When your thread finishes it really finishes. OS will never switch context to it because there is nowhere to switch context to. But your std::thread object will still exist and you still be able to call join
on it. And it will behave properly: return as soon as the thread will finish, in your case, instantly.
Upvotes: 2