Should destructors be threadsafe?

后端 未结 9 1313
误落风尘
误落风尘 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:48

    Old question, but still valid IMHO.

    In general, public members of a class altering a critical section, accessible from different threads should lock this critical section. But destruction of an object is the ultimate alteration of the state of an object including the critical section.

    So if there are async operations going on, where this critical state of the object is entered, destruction should definitely wait until that critical section is left again. One way to do it, is to use locking in the destructor. Surely that doesn't help to guarantee the object itself isn't accessed erroneously anymore afterwards.

    But that technique can be used to sync. destruction of the object with ending of the async. operation on the critical section.

提交回复
热议问题