What is different between join() and detach() in multi threading in C++?
Does join() kill the thread?
join() doesn't kill the thread. Actually it waits until thread main function returns. So if your thread main function looks like this:
while (true) {
}
join() is going to wait forever.
detatch() doesn't kill thread either. Actually it tells std::thread that this thread should continue to run even when std::thread object is destroyed. C++ checks in std::thread destructor that thread is either joined or detached and terminates program if this check fails.
So if you uncomment first line in main function of the following code it will crash. If you uncomment second or third line it will work ok.
#include
void func() {
}
void fail1() {
std::thread t(func);
// will fail when we try to destroy t since it is not joined or detached
}
void works1() {
std::thread t(func);
t.join();
}
void works2() {
std::thread t(func);
t.detach();
}
int main() {
// fail1();
// works1();
// works2();
}