Elim cr-checkbox
[chromium-blink-merge.git] / ppapi / utility / threading / lock.h
blobf3bfe4adebde65836e780cbad9a50ba68c54329d
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.
5 #ifndef PPAPI_UTILITY_THREADING_LOCK_H_
6 #define PPAPI_UTILITY_THREADING_LOCK_H_
8 #ifdef WIN32
9 #include <windows.h>
10 #else
11 #include <pthread.h>
12 #endif
14 namespace pp {
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();
22 /// Destroys the lock.
23 ~Lock();
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();
33 /// Releases the lock. This must be paired with a call to Acquire().
34 void Release();
36 private:
37 #if defined(WIN32)
38 typedef CRITICAL_SECTION OSLockType;
39 #else
40 typedef pthread_mutex_t OSLockType;
41 #endif
43 OSLockType os_lock_;
45 // Copy and assign not supported.
46 Lock(const Lock&);
47 Lock& operator=(const Lock&);
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:
66 explicit AutoLock(Lock& lock) : lock_(lock) {
67 lock_.Acquire();
70 ~AutoLock() {
71 lock_.Release();
74 private:
75 Lock& lock_;
77 // Copy and assign not supported.
78 AutoLock(const AutoLock&);
79 AutoLock& operator=(const AutoLock&);
82 } // namespace pp
84 #endif // PPAPI_UTILITY_THREADING_LOCK_H_