Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely delete a thread pointer in a destructor?

Say, I have a C++ class including a thread pointer as a member variable. The thread keeps running until the program exits. If I delete the pointer in the destructor, it seems that the thread has not yet finished at that moment? What is the best practice to manage this or any tricks?

Sample code:

class Car {
public:
    Car();
    ~Car();
private:
    boost::thread *m_runningThreadPtr;
};


Car::Car() {
    m_runningThreadPtr = new boost::thread();
}

Car::~Car() {
    delete m_runningThreadPtr;    // The thread should be still running now. 
                                  // Problematic if it was deleted here?
}
like image 861
lichgo Avatar asked Oct 31 '22 15:10

lichgo


1 Answers

By default the destructor will call terminate() to kill the thread if it's still running, whether this is safe or not depends on what the thread is doing at the time. You can call join() before deleting it if you want to wait for the thread to finish, and use some sort of synchronization system (even just a global flag) that tells the thread to quit.

like image 109
Jonathan Potter Avatar answered Nov 15 '22 05:11

Jonathan Potter