Should destructors be threadsafe?

2019-03-24 07:45发布

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

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

//Access Data Members, **NO Global** members are being accessed here


  LeaveCriticalSection(&cs);
}

I am wondering will it help by any chance to guard the destructor ?

Consider a scenario :

1. Thread1 - About to execute any of the member function which uses critical section
2. Thread2-  About to execute destructor.

If the order of execution is 1=>2 then it might work. But what if the order is reversed ?

Is it a design issue ?

8条回答
你好瞎i
2楼-- · 2019-03-24 08:40

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).

查看更多
爷的心禁止访问
3楼-- · 2019-03-24 08:41

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.

查看更多
登录 后发表回答