Original Post
This class is inherited by any other class to make it thread-safe. I was wondering how thread-safe this code really is. Any help is appreciated.
class ThreadLock
{
volatile bool locked_;
public:
// unlocked upon instantiation
ThreadLock()
{
locked_ = false;
}
// waits for a turn and locks the object
void Lock()
{
while( locked_ );
locked_ = true;
}
// returns true on success, or false on timeout
bool Lock( double timeout )
{
clock_t timeout2 = clock_t( timeout * CLOCKS_PER_SEC );
clock_t start = ::clock();
while( locked_ )
if( ::clock() - start > timeout2 )
return false;
locked_ = true;
return true;
}
// unlocks the object
void Unlock()
{
locked_ = false;
}
// returns the status of the lock
bool IsLocked() const
{
return locked_;
}
};