|
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 Lock() : lock_() {} |
|
15 ~Lock() {} |
|
16 void Acquire() { lock_.Lock(); } |
|
17 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 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 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 explicit AutoLock(Lock& lock) : lock_(lock) { |
|
43 lock_.Acquire(); |
|
44 } |
|
45 |
|
46 ~AutoLock() { |
|
47 lock_.AssertAcquired(); |
|
48 lock_.Release(); |
|
49 } |
|
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_ |