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.
9 #include "base/lock_impl.h"
11 // A convenient wrapper for an OS specific critical section. The only real
12 // intelligence in this class is in debug mode for the support for the
13 // AssertAcquired() method.
17 #if defined(NDEBUG) // Optimized wrapper implementation
20 void Acquire() { lock_
.Lock(); }
21 void Release() { lock_
.Unlock(); }
23 // If the lock is not held, take it and return true. If the lock is already
24 // held by another thread, immediately return false. This must not be called
25 // by a thread already holding the lock (what happens is undefined and an
26 // assertion may fail).
27 bool Try() { return lock_
.Try(); }
29 // Null implementation if not debug.
30 void AssertAcquired() const {}
35 // NOTE: Although windows critical sections support recursive locks, we do not
36 // allow this, and we will commonly fire a DCHECK() if a thread attempts to
37 // acquire the lock a second time (while already holding it).
48 bool rv
= lock_
.Try();
55 void AssertAcquired() const;
59 // The posix implementation of ConditionVariable needs to be able
60 // to see our lock and tweak our debugging counters, as it releases
61 // and acquires locks inside of pthread_cond_{timed,}wait.
62 // Windows doesn't need to do this as it calls the Lock::* methods.
63 friend class ConditionVariable
;
68 // Members and routines taking care of locks assertions.
69 // Note that this checks for recursive locks and allows them
70 // if the variable is set. This is allowed by the underlying implementation
71 // on windows but not on Posix, so we're doing unneeded checks on Posix.
72 // It's worth it to share the code.
73 void CheckHeldAndUnmark();
74 void CheckUnheldAndMark();
76 // All private data is implicitly protected by lock_.
77 // Be VERY careful to only access members under that lock.
79 // Determines validity of owning_thread_id_. Needed as we don't have
80 // a null owning_thread_id_ value.
81 bool owned_by_thread_
;
82 PlatformThreadId owning_thread_id_
;
85 LockImpl lock_
; // Platform specific underlying lock implementation.
87 DISALLOW_COPY_AND_ASSIGN(Lock
);
90 // A helper class that acquires the given Lock while the AutoLock is in scope.
93 explicit AutoLock(Lock
& lock
) : lock_(lock
) {
98 lock_
.AssertAcquired();
104 DISALLOW_COPY_AND_ASSIGN(AutoLock
);
107 // AutoUnlock is a helper that will Release() the |lock| argument in the
108 // constructor, and re-Acquire() it in the destructor.
111 explicit AutoUnlock(Lock
& lock
) : lock_(lock
) {
112 // We require our caller to have the lock.
113 lock_
.AssertAcquired();
123 DISALLOW_COPY_AND_ASSIGN(AutoUnlock
);
126 #endif // BASE_LOCK_H_