1 /*
2  *  Copyright 2011 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef WEBRTC_BASE_SHAREDEXCLUSIVELOCK_H_
12 #define WEBRTC_BASE_SHAREDEXCLUSIVELOCK_H_
13 
14 #include "webrtc/base/constructormagic.h"
15 #include "webrtc/base/criticalsection.h"
16 #include "webrtc/base/event.h"
17 
18 namespace rtc {
19 
20 // This class provides shared-exclusive lock. It can be used in cases like
21 // multiple-readers/single-writer model.
22 class LOCKABLE SharedExclusiveLock {
23  public:
24   SharedExclusiveLock();
25 
26   // Locking/unlocking methods. It is encouraged to use SharedScope or
27   // ExclusiveScope for protection.
28   void LockExclusive() EXCLUSIVE_LOCK_FUNCTION();
29   void UnlockExclusive() UNLOCK_FUNCTION();
30   void LockShared();
31   void UnlockShared();
32 
33  private:
34   rtc::CriticalSection cs_exclusive_;
35   rtc::CriticalSection cs_shared_;
36   rtc::Event shared_count_is_zero_;
37   int shared_count_;
38 
39   RTC_DISALLOW_COPY_AND_ASSIGN(SharedExclusiveLock);
40 };
41 
42 class SCOPED_LOCKABLE SharedScope {
43  public:
SharedScope(SharedExclusiveLock * lock)44   explicit SharedScope(SharedExclusiveLock* lock) SHARED_LOCK_FUNCTION(lock)
45       : lock_(lock) {
46     lock_->LockShared();
47   }
48 
UNLOCK_FUNCTION()49   ~SharedScope() UNLOCK_FUNCTION() { lock_->UnlockShared(); }
50 
51  private:
52   SharedExclusiveLock* lock_;
53 
54   RTC_DISALLOW_COPY_AND_ASSIGN(SharedScope);
55 };
56 
57 class SCOPED_LOCKABLE ExclusiveScope {
58  public:
ExclusiveScope(SharedExclusiveLock * lock)59   explicit ExclusiveScope(SharedExclusiveLock* lock)
60       EXCLUSIVE_LOCK_FUNCTION(lock)
61       : lock_(lock) {
62     lock_->LockExclusive();
63   }
64 
UNLOCK_FUNCTION()65   ~ExclusiveScope() UNLOCK_FUNCTION() { lock_->UnlockExclusive(); }
66 
67  private:
68   SharedExclusiveLock* lock_;
69 
70   RTC_DISALLOW_COPY_AND_ASSIGN(ExclusiveScope);
71 };
72 
73 }  // namespace rtc
74 
75 #endif  // WEBRTC_BASE_SHAREDEXCLUSIVELOCK_H_
76