Reputation: 901
class MyClass
{
...
...
CCriticalSection m_Cs;
void MyFunction()
{
m_Cs.Lock();
.....
m_Cs.Unlock();
}
MyClass::~MyClass()
{
....
}
};
I am using Critical Section in my class as above, myFunction is called by Thread 1, and when myFunction is in progress Thread 2 is deleting the object. So Unlock is crashing.
So I decided to modify MyClass destructor as below
MyClass::~MyClass()
{
m_Cs.Lock();
m_Cs.Unlock();
....
}
This resolves my crash, because when the Thread 1 is accessing MyFunction CriticalSection is locked, so when the object is being deleted from Thread 2, the CriticalSection.Lock in Destructor is blocked until unlock is called from MyFunction. Is this right behaviour to Lock and unLock CriticalSection from destructor to avoid this crash?
Upvotes: 0
Views: 818
Reputation: 7479
No, this is not the correct approach, because it does not protect the scenario where thread 2 deletes the object before thread 1 calls MyFunction.
You currently have a Dangling Pointer bug in your code.
The correct solution is to modify your code to ensure that deletion of the object happens at a time when no other thread can use it. Common approaches to this include:
Upvotes: 1