I found this stack-overflow question about this but it is 11 years old and I was wondering if there's a better way to do this as the question was posted in C++11 times.
There is std::thread::joinable()
but the problem is that even if the thread finished executing, it will still be marked as joinable
, if it hasn't been joined with std::thread::join()
.
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. docs
I could use an std::atomic<bool> threadFinished = false;
and set it to true
in the thread right before it finishes (this is mentioned in the answer of the stack-overflow question I mentioned at the beginning of this question).
Something like this:
std::atomic<bool> threadFinished = false;
std::thread myThread([&threadFinished]() {
std::this_thread::wait(1000);
threadFinished = true;
});
while (true) {
if (threadFinished) {
// Thread finished executing (note: myThread.joinable() is still true)
break;
}
}
myThread.join();
But this seems very unclean and unscalable, especially if you have many return points in the thread. Is there a better way to accomplish this?