Here is a quick example:
class worker
{
std::thread thread1;
std::thread thread2;
worker(){}
start()
{
thread1 = std::thread([]()
{
std::this_thread::sleep_for(std::chrono::milliseconds(50000));
});
thread1.deteach();
thread2 = std::thread([]()
{
std::this_thread::sleep_for(std::chrono::milliseconds(50000));
});
thread2.deteach();
}
~worker()
{
// Ignore this part! - as per Richard's comment :)
//thread1.join(); // <-- do I need this at all?
//thread2.join(); // <-- do I need this at all?
}
}
int main()
{
worker *p_worker = new worker();
p_worker->start();
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 1 sec
delete p_worker;
}
- Create the worker
- Start the threads which last for 50 seconds
- After 1 second delete the worker (calls destructor)
- In worker destructor I re-join the threads (probably should check if they are joinable first?) - not really sure I need to do this.
- Then worker is destroyed
I had a look at this question: how-do-i-terminate-a-thread-in-c11 which suggests there is no c11 portable way to terminate the threads.
Questions:
- Are the threads destroyed completely (no dregs/leaks left)?
- If "yes" do I need to re-join the threads in order for them to be destroyed?
EDIT - Richard pointed out this is N/A
- If "yes" do I need to re-join the threads in order for them to be destroyed?
- Is this a sensible approach?