1 // Copyright (c) 2006-2008 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_IMPL_H_ 6 #define BASE_LOCK_IMPL_H_ 7 8 #include "build/build_config.h" 9 10 #if defined(OS_WIN) 11 #include <windows.h> 12 #elif defined(OS_POSIX) 13 #include <pthread.h> 14 #endif 15 16 #include "base/basictypes.h" 17 #include "base/platform_thread.h" 18 19 // This class implements the underlying platform-specific spin-lock mechanism 20 // used for the Lock class. Most users should not use LockImpl directly, but 21 // should instead use Lock. 22 class LockImpl { 23 public: 24 #if defined(OS_WIN) 25 typedef CRITICAL_SECTION OSLockType; 26 #elif defined(OS_POSIX) 27 typedef pthread_mutex_t OSLockType; 28 #endif 29 30 LockImpl(); 31 ~LockImpl(); 32 33 // If the lock is not held, take it and return true. If the lock is already 34 // held by something else, immediately return false. 35 bool Try(); 36 37 // Take the lock, blocking until it is available if necessary. 38 void Lock(); 39 40 // Release the lock. This must only be called by the lock's holder: after 41 // a successful call to Try, or a call to Lock. 42 void Unlock(); 43 44 // Debug-only method that will DCHECK() if the lock is not acquired by the 45 // current thread. In non-debug builds, no check is performed. 46 // Because linux and mac condition variables modify the underlyning lock 47 // through the os_lock() method, runtime assertions can not be done on those 48 // builds. 49 #if defined(NDEBUG) || !defined(OS_WIN) AssertAcquired()50 void AssertAcquired() const {} 51 #else 52 void AssertAcquired() const; 53 #endif 54 55 // Return the native underlying lock. Not supported for Windows builds. 56 // TODO(awalker): refactor lock and condition variables so that this is 57 // unnecessary. 58 #if !defined(OS_WIN) os_lock()59 OSLockType* os_lock() { return &os_lock_; } 60 #endif 61 62 private: 63 OSLockType os_lock_; 64 65 #if !defined(NDEBUG) && defined(OS_WIN) 66 // All private data is implicitly protected by lock_. 67 // Be VERY careful to only access members under that lock. 68 PlatformThreadId owning_thread_id_; 69 int32 recursion_count_shadow_; 70 bool recursion_used_; // Allow debugging to continued after a DCHECK(). 71 #endif // NDEBUG 72 73 DISALLOW_COPY_AND_ASSIGN(LockImpl); 74 }; 75 76 77 #endif // BASE_LOCK_IMPL_H_ 78