Can I re-join a thread after detaching from it? A while ago I read somewhere that you should call either join or detach immediately after creating a thread.
Can I detach from a thread and then re-join it later?
Example:
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
int main()
{
auto task = []()
{
std::this_thread::sleep_for(3s);
std::cout << "Job thread done" << std::endl;
};
std::thread t(task);
t.detach(); //Detach from thread and do our own thing...
//Do something
std::this_thread::sleep_for(1s);
std::cout << "Main thread done" << std::endl;
//Wait for job thread to finish if it is not finished
t.join();
std::cout << "Everything done" << std::endl;
return 0;
}