michael@0: // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #ifndef BASE_LOCK_H_ michael@0: #define BASE_LOCK_H_ michael@0: michael@0: #include "base/lock_impl.h" michael@0: michael@0: // A convenient wrapper for an OS specific critical section. michael@0: michael@0: class Lock { michael@0: public: michael@0: Lock() : lock_() {} michael@0: ~Lock() {} michael@0: void Acquire() { lock_.Lock(); } michael@0: void Release() { lock_.Unlock(); } michael@0: // If the lock is not held, take it and return true. If the lock is already michael@0: // held by another thread, immediately return false. michael@0: bool Try() { return lock_.Try(); } michael@0: michael@0: // In debug builds this method checks that the lock has been acquired by the michael@0: // calling thread. If the lock has not been acquired, then the method michael@0: // will DCHECK(). In non-debug builds, the LockImpl's implementation of michael@0: // AssertAcquired() is an empty inline method. michael@0: void AssertAcquired() const { return lock_.AssertAcquired(); } michael@0: michael@0: // Return the underlying lock implementation. michael@0: // TODO(awalker): refactor lock and condition variables so that this is michael@0: // unnecessary. michael@0: LockImpl* lock_impl() { return &lock_; } michael@0: michael@0: private: michael@0: LockImpl lock_; // Platform specific underlying lock implementation. michael@0: michael@0: DISALLOW_COPY_AND_ASSIGN(Lock); michael@0: }; michael@0: michael@0: // A helper class that acquires the given Lock while the AutoLock is in scope. michael@0: class AutoLock { michael@0: public: michael@0: explicit AutoLock(Lock& lock) : lock_(lock) { michael@0: lock_.Acquire(); michael@0: } michael@0: michael@0: ~AutoLock() { michael@0: lock_.AssertAcquired(); michael@0: lock_.Release(); michael@0: } michael@0: michael@0: private: michael@0: Lock& lock_; michael@0: DISALLOW_COPY_AND_ASSIGN(AutoLock); michael@0: }; michael@0: michael@0: // AutoUnlock is a helper that will Release() the |lock| argument in the michael@0: // constructor, and re-Acquire() it in the destructor. michael@0: class AutoUnlock { michael@0: public: michael@0: explicit AutoUnlock(Lock& lock) : lock_(lock) { michael@0: // We require our caller to have the lock. michael@0: lock_.AssertAcquired(); michael@0: lock_.Release(); michael@0: } michael@0: michael@0: ~AutoUnlock() { michael@0: lock_.Acquire(); michael@0: } michael@0: michael@0: private: michael@0: Lock& lock_; michael@0: DISALLOW_COPY_AND_ASSIGN(AutoUnlock); michael@0: }; michael@0: michael@0: #endif // BASE_LOCK_H_