How to safely remove a stream pointer in a destructor?

Let's say I have a C ++ class that includes a stream pointer as a member variable. The thread continues to run until the program exits. If I delete the pointer in the destructor, it seems that the thread is not finished at this moment? What is the practice to manage this or any tricks?

Code example:

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? } 
+5
source share
4 answers

By default, the destructor will call terminate() to kill the thread if it is still running, regardless of whether it is safe or not, depending on what the thread is doing at that time. You can call join() before deleting it, if you want to wait until the stream ends, and use some synchronization system (even a global flag) that tells the stream to exit.

+1
source

It depends on what kind of behavior you are looking for.

If you want to delete an object and stop its stream object, and then delete its stream object, then you should have a stop flag that your stream checks from time to time. In the destructor, you set the stop flag, and then call join() in your thread. Once he returns, you can safely remove the pointer.

If, on the other hand, you want to delete the object and continue the thread until it ends, you will need a smarter mechanism, for example, at the end of your thread function, placing a callback in the main thread of your application that calls join() in your thread and then delete it. For this, of course, you need a pointer to your stream object in your stream function.

EDIT In the case of boost::thread it just detaches in its destructor, so for the second option, you can safely remove it when you're done. It is important to note, however, that this will not work with the std::thread destructor, which will then terminate your program. But then you can also manually call detach() and then delete . So you really need to look at the API you are using.

+1
source

Do not delete it. Remove the thread when done.

0
source

Your program runs when there is no more code to run. Are your threads still running code? Then why do you think your program is complete?

So, it is reasonable to assume that I really made your flows. This means that you can call .join() on the stream, after which you can call delete .

0
source

Source: https://habr.com/ru/post/1204548/


All Articles