1 : // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
2 : // Use of this source code is governed by a BSD-style license that can be
3 : // found in the LICENSE file.
4 :
5 : #ifndef BASE_LOCK_H_
6 : #define BASE_LOCK_H_
7 :
8 : #include "base/lock_impl.h"
9 :
10 : // A convenient wrapper for an OS specific critical section.
11 :
12 : class Lock {
13 : public:
14 14376 : Lock() : lock_() {}
15 11488 : ~Lock() {}
16 93226 : void Acquire() { lock_.Lock(); }
17 93226 : void Release() { lock_.Unlock(); }
18 : // If the lock is not held, take it and return true. If the lock is already
19 : // held by another thread, immediately return false.
20 : bool Try() { return lock_.Try(); }
21 :
22 : // In debug builds this method checks that the lock has been acquired by the
23 : // calling thread. If the lock has not been acquired, then the method
24 : // will DCHECK(). In non-debug builds, the LockImpl's implementation of
25 : // AssertAcquired() is an empty inline method.
26 87552 : void AssertAcquired() const { return lock_.AssertAcquired(); }
27 :
28 : // Return the underlying lock implementation.
29 : // TODO(awalker): refactor lock and condition variables so that this is
30 : // unnecessary.
31 1418 : LockImpl* lock_impl() { return &lock_; }
32 :
33 : private:
34 : LockImpl lock_; // Platform specific underlying lock implementation.
35 :
36 : DISALLOW_COPY_AND_ASSIGN(Lock);
37 : };
38 :
39 : // A helper class that acquires the given Lock while the AutoLock is in scope.
40 : class AutoLock {
41 : public:
42 87552 : explicit AutoLock(Lock& lock) : lock_(lock) {
43 87552 : lock_.Acquire();
44 87552 : }
45 :
46 87552 : ~AutoLock() {
47 87552 : lock_.AssertAcquired();
48 87552 : lock_.Release();
49 87552 : }
50 :
51 : private:
52 : Lock& lock_;
53 : DISALLOW_COPY_AND_ASSIGN(AutoLock);
54 : };
55 :
56 : // AutoUnlock is a helper that will Release() the |lock| argument in the
57 : // constructor, and re-Acquire() it in the destructor.
58 : class AutoUnlock {
59 : public:
60 : explicit AutoUnlock(Lock& lock) : lock_(lock) {
61 : // We require our caller to have the lock.
62 : lock_.AssertAcquired();
63 : lock_.Release();
64 : }
65 :
66 : ~AutoUnlock() {
67 : lock_.Acquire();
68 : }
69 :
70 : private:
71 : Lock& lock_;
72 : DISALLOW_COPY_AND_ASSIGN(AutoUnlock);
73 : };
74 :
75 : #endif // BASE_LOCK_H_
|