I am in situation where there are two classes. Derived class with operator== overloading with mutex lock and Base class with operator== overloading with another mutex lock. On calling operator== function using Derived class object, I am calling base class operator== overloading as a return variable. It is shown as below:
class DMutex
{
public:
static pthread_mutex_t* GetMutex()
{
static pthread_mutex_t mutexRes = PTHREAD_MUTEX_INITIALIZER;
return &mutexRes;
}
DMutex()
{
pthread_mutex_lock(DMutex::GetMutex());
}
~DMutex()
{
pthread_mutex_unlock(DMutex::GetMutex());
}
};
// This is the class we are not allowed to modify
class Base
{
public:
char* m_text;
// some more operator overloaded fucntion is written to initialize base class m_text varaible
bool operator==(const Base& other) const
{
CriticalSectionLocker lock(GetCriticalSection()); // mutex lock which gets unlocked in DMutex class destructor
return (m_text == other.m_text);
}
};
// This claas can be modified
class Derived : public Base
{
public:
// some more operator overloaded fucntion is written to initialize base class m_text varaible
bool operator==(const Base& string) const
{
DMutex dMutex; // mutex lock which gets unlocked in DMutex class destructor
return Base::operator==(string); // calling base class operator==
} // here dMutex is destroying
};
int main()
{
Derived d1 = "some text";
Derived d2 = "some other text"'
if(d1==d2)
{
//some code
}
}
Derived class locks the mutex inside Derived::operator==() function, it will eventually call the base class operator==() function where one more mutex lock is given. The problem arises when the dMutex object gets destroyed which unlocks the mutex there and with that Derived class object also gets deleted which eventually deletes the base class object memory. Since because Base class mutex lock is yet to unlock, base class memory getting deleted first sometimes winch is causing crash.
Please provide some solution. Note: We can not modify anything in base class.
Aucun commentaire:
Enregistrer un commentaire