Back to questionsWhat happens if a
JuniorTheoryVery common
What happens if a std::thread is destroyed without join or detach?
#include <iostream>
#include <thread>
void greet() {
std::cout << "hi\n";
}
int main() {
std::thread t(greet);
}The program is aborted by std::terminate: t was neither joined nor detached
- Expecting the destructor to join:
std::jthreaddoes that, but astd::threaddestroyed withoutjoin()ordetach()callsstd::terminate. - Expecting an automatic
detach(): a silently detached thread could outlive the data it uses, which is why the destructor callsstd::terminateinstead.
- How does
std::jthreadimprove this? - When is
detachacceptable?