Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running method while destroying the object

A few days ago my friend told me about the situation, they had in their project. Someone decided, that it would be good to destroy the object of NotVerySafeClass in parallel thread (like asynchronously). It was implemented some time ago. Now they get crashes, because some method is called in main thread, while object is destroyed. Some workaround was created to handle the situation.

Ofcourse, this is just an example of not very good solution, but still the question:

Is there some way to prevent the situation internally in NotVerySafeClass (deny running the methods, if destructor was called already, and force the destructor to wait, until any running method is over (let's assume there is only one method))?

like image 445
Werolik Avatar asked Sep 13 '11 09:09

Werolik


1 Answers

No, no and no. This is a fundamental design issue, and it shows a common misconception in thinking about multithreaded situations and race conditions in general.

There is one thing that can happen equally likely, and this is really showing that you need an ownership concept: The function calling thread could call the function just right after the object has been destroyed, so there is no object anymore and try to call a function on it is UB, and since the object does not exist anymore, it also has no chance to prevent any interaction between the dtor and a member function.

like image 158
PlasmaHH Avatar answered Oct 12 '22 21:10

PlasmaHH