Should destructors be threadsafe?

后端 未结 9 1309
误落风尘
误落风尘 2021-02-07 09:08

I was going through a legacy code and found the following snippet:

MyClass::~MyClass()
{
   EnterCriticalSection(&cs);

//Access Data Members, **NO Global**          


        
相关标签:
9条回答
  • 2021-02-07 09:56

    Define "thread safe". These are possibly the two most ill-understood words in modern computing.

    But if there is a possibility of the destructor being entered twice from two different threads (as the use of symchronisation objects implies) your code is in deep doo-doo. The objects that are deleting the object that you are asking about should be managing this - it is (probably) at that level that synchronisation should be taking place.

    0 讨论(0)
  • 2021-02-07 09:58

    I second the comment from Neil ButterWorth. Absolutely, the Entities responsible for deleting and accessing the myclass, should have a check on this.

    This synchronisation will start actually from the moment the object of type MyClass is created.

    0 讨论(0)
  • 2021-02-07 10:00

    The destructor should not be called when the object is in use. If you're dealing with such a situation, it needs a fundamental fix. However, the destructor might want to alter some other thing (which is unrelated to the class being destructed) and it might need a critical section (e.g. like decrementing a global counter).

    0 讨论(0)
提交回复
热议问题