我正在审查一位同事的 Visual Studio 2008 C++03 应用程序,并且遇到了线程同步原语的实现(如下)。
假设SyncObject
正确实现,在下面的代码中使用布尔值来了解资源是锁定还是解锁线程安全?如果不是,您能否通过“ThreadA”执行此操作而“ThreadB”执行此操作,以便我理解您的逻辑?
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_;
};