析构函数应该是线程安全的吗? [英] Should destructors be threadsafe?

查看:171
本文介绍了析构函数应该是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看旧代码,发现以下代码段:

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 ?

考虑一种情况:

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

如果执行顺序为1 => 2,则可能有效。但是,如果顺序颠倒了怎么办?

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

这是设计问题吗?

推荐答案

在使用对象时,不应调用析构函数。如果您正在处理这种情况,它需要一个基本的解决方法。但是,析构函数可能想要更改其他内容(与被破坏的类无关),并且可能需要一个关键部分(例如,减少 global 计数器)。

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

这篇关于析构函数应该是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆