std::thread::join()
is permitted to fail, throwing a std::system_error
for no_such_process
if the thread is "not valid". Note that the no_such_process
case is distinct from a thread that is not joinable (for which the error code is invalid_argument
).
In what circumstances might that happen? Alternatively, what must I do to ensure that join()
does not fail for that reason? I want a destructor to join()
some threads it manages, and of course I want the destructor to never throw exceptions. What can make a (properly constructed and not destroyed) thread "not valid".
When thread::join() returns, the OS thread of execution has completed and the C++ thread object can be destroyed.
The join part means the main program will wait for the thread to end before continuing. Without join, the main program will end and the thread will continue.
Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated.
To wait for a thread use the std::thread::join() function. This function makes the current thread wait until the thread identified by *this has finished executing. A C++ program is given below. It launches three thread from the main function.
In what circumstances might that happen?
On *nix systems, it happens when you try to join a thread whose ID is not in the thread table, meaning the thread does not exist (anymore). This might happen when a thread has already been joined and terminated, or if your thread variable's memory has been corrupted.
Alternatively, what must I do to ensure that join() does not fail for that reason?
You might test std::thread::joinable()
, but it might also fail1. Just don't mess with your thread variables, and you're good to go. Simply ignore this possibility, if you encounter such an error your program better core dump and let you analyse the bug.
1) By fail, I mean report true
instead of false
or the other way around, not throw or crash.
The no_such_process
error code corresponds to a ESRCH
POSIX error code. On a POSIX system std::thread::join()
probably delegates to pthread_join()
.
ESRCH
.pthread_join
may give ESRCH
if no thread with the given thread ID could be found. The ID of a C++ thread is private data, so the only way the ID could be not found would be if this
does not point to a properly constructed std::thread
.I conclude that this error condition can only occur as a result of an earlier action that had undefined behaviour, such as a bad reinterpret_cast
or use of a dangling pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With