Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor vs member function race again

I've already seen similar question: Destructor vs member function race .. but didn't find the answer for the following. Suppose we have a class owning some worker thread. Destructor of the class can look like:

~OurClass
{
    ask_the_thread_to_terminate;
    wait_for_the_thread_to_terminate;
    ....
    do_other_things;
}

The question is: may we call OurClass's member functions in the worker thread as we are sure all these calls will be done before do_other_things in the destructor?

like image 859
a-b Avatar asked Mar 19 '23 19:03

a-b


2 Answers

Yes you can. Destruction of member variables willonly start after do_other_things completes its execution. It is safe to call member functions before object gets destructed.

like image 109
Abhishek Bansal Avatar answered Apr 01 '23 20:04

Abhishek Bansal


Well, you kinda can do that, but it's easy to make a mistake this way. For example, if you do something like:

~OurClass
{
    delete *memberPointer_; 
    ask_the_thread_to_terminate; // the thread calls OurClass::foo();
    wait_for_the_thread_to_terminate;
    ....
    do_other_things
}

void OurClass::foo()
{
    memberPointer->doSomething();
}

you will be in trouble. It also makes it harder to read through the code. So you will have to be careful with the order of operations and stuff like that. In general if it's possible to change the architecture to avoid such complicated constructions, I would suggest to do it.

like image 44
SingerOfTheFall Avatar answered Apr 01 '23 19:04

SingerOfTheFall