1 // Copyright (c) 2012 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 PPAPI_UTILITY_THREADING_LOCK_H_ 6 #define PPAPI_UTILITY_THREADING_LOCK_H_ 7 8 #ifdef WIN32 9 #include <windows.h> 10 #else 11 #include <pthread.h> 12 #endif 13 14 namespace pp { 15 16 /// A simple wrapper around a platform-specific lock. See also AutoLock. 17 class Lock { 18 public: 19 /// Creates a lock in the "not held" state. 20 Lock(); 21 22 /// Destroys the lock. 23 ~Lock(); 24 25 /// Acquires the lock, blocking if it's already held by a different thread. 26 /// The lock must not already be held on the current thread (i.e. recursive 27 /// locks are not supported). 28 /// 29 /// Most callers should consider using an AutoLock instead to automatically 30 /// acquire and release the lock. 31 void Acquire(); 32 33 /// Releases the lock. This must be paired with a call to Acquire(). 34 void Release(); 35 36 private: 37 #if defined(WIN32) 38 typedef CRITICAL_SECTION OSLockType; 39 #else 40 typedef pthread_mutex_t OSLockType; 41 #endif 42 43 OSLockType os_lock_; 44 45 // Copy and assign not supported. 46 Lock(const Lock&); 47 Lock& operator=(const Lock&); 48 }; 49 50 /// A helper class that scopes holding a lock. 51 /// 52 /// @code 53 /// class MyClass { 54 /// public: 55 /// void DoSomething() { 56 /// pp::AutoLock lock(lock_); 57 /// ...do something with the lock held... 58 /// } 59 /// 60 /// private: 61 /// pp::Lock lock_; 62 /// }; 63 /// @endcode 64 class AutoLock { 65 public: AutoLock(Lock & lock)66 explicit AutoLock(Lock& lock) : lock_(lock) { 67 lock_.Acquire(); 68 } 69 ~AutoLock()70 ~AutoLock() { 71 lock_.Release(); 72 } 73 74 private: 75 Lock& lock_; 76 77 // Copy and assign not supported. 78 AutoLock(const AutoLock&); 79 AutoLock& operator=(const AutoLock&); 80 }; 81 82 } // namespace pp 83 84 #endif // PPAPI_UTILITY_THREADING_LOCK_H_ 85