I have am reviewing a colleague’s Visual Studio 2008 C++03 application application and I’ve come across an implementation of a thread synchronization primitive (below).
Assuming SyncObject is implemented correctly, is the use of a boolean in the below code to know if the resource is locked or unlocked thread-safe? If no, can you walk through a “ThreadA” does this and “ThreadB” does that situation so I understand your logic?
class CMyLock
{
public:
CMyLock(SyncObject* object)
: object_(object), acquired_(false)
{
};
// return true if the resource is locked within the given timeout period
bool Lock(DWORD dwTimeOut = INFINITE)
{
acquired_ = object_->Lock(dwTimeOut);
return acquired_;
};
// return true if the resource is unlocked
bool Unlock()
{
if (acquired_)
acquired_ = !object_->Unlock();
return !acquired_;
};
// return true if the resource is locked
bool IsLocked() { return acquired_; };
private:
bool acquired_;
// some thread synchronization primitive
SyncObject* object_;
};
It is not threadsafe.
directly after
m_pObject->Unlock()returns, another thread waiting onm_pObject->Lock(dwTimeOut)can return and setm_bAcquiredto true, then the unlocking thread setsm_bAcquiredto false and overwrites the locked state incorrectly (IsLocked will return false while the object is locked).