2

I have a class object whose functions can be called from different threads.

It is possible to get into a situation where Thread1(T1) is calling destructor,
whereas Thread(T2) is executing some other function on the same object.

Let's say T1 is able to call the destructor first, then what happens to the code running in T2?
Will it produce a crash or since the object is already destroyed, the member function will stop running?

Will taking a mutex lock at entry and unlocking at exit of all class functions ensure that there is no crash in any kind of race that will happen between destructor and member functions?

Appreciate your help!

Aman Jain
  • 10,927
  • 15
  • 50
  • 63
  • 2
    Undefined behavior, cf. [Running method while destroying the object](http://stackoverflow.com/questions/7399316/running-method-while-destroying-the-object) – maddouri Oct 11 '15 at 17:46
  • 'It is possible to get into a situation where Thread1(T1) is calling destructor, whereas Thread(T2) is executing some other function on the same object.' - well, change your design so that it does not happen. If you do bad things, bad things will ensue. – Martin James Oct 12 '15 at 09:23

2 Answers2

0

What you'll get is unknown and unpredictable. You're describing a classic multithreading bug / poor design.

An instance should be properly locked before use, and that includes destruction. Once you do that, it's impossible to call a member function on an instance that's being destroyed in another thread.

Locking inside the functions won't help since if 2 separate threads hold references to the same instance and 1 of them causes it to be destroyed, the other thread is holding a bad reference and doesn't know that. A typical solution is to use refcounts, where destruction is at the responsibility of the object itself once no references to it exist. In C++, you'd usually use shared_ptr<> to do this.

Amit
  • 45,440
  • 9
  • 78
  • 110
0

No. Because the logic is flawed. If it is possible at all that T1 is calling the destructor, a mutex will not prevent it from still trying to do that.

There is shared data between T1 and T2 and as such you must make sure that neither will try to call methods on a non-existing shared object.

A mutex alone will not help.

emvee
  • 4,371
  • 23
  • 23