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?
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With