henrike@webrtc.org | f7795df | 2014-05-13 18:00:26 +0000 | [diff] [blame^] | 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 SharedExclusiveLock { |
| 23 | public: |
| 24 | SharedExclusiveLock(); |
| 25 | |
| 26 | // Locking/unlocking methods. It is encouraged to use SharedScope or |
| 27 | // ExclusiveScope for protection. |
| 28 | void LockExclusive(); |
| 29 | void UnlockExclusive(); |
| 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 | DISALLOW_COPY_AND_ASSIGN(SharedExclusiveLock); |
| 40 | }; |
| 41 | |
| 42 | class SharedScope { |
| 43 | public: |
| 44 | explicit SharedScope(SharedExclusiveLock* lock) : lock_(lock) { |
| 45 | lock_->LockShared(); |
| 46 | } |
| 47 | |
| 48 | ~SharedScope() { |
| 49 | lock_->UnlockShared(); |
| 50 | } |
| 51 | |
| 52 | private: |
| 53 | SharedExclusiveLock* lock_; |
| 54 | |
| 55 | DISALLOW_COPY_AND_ASSIGN(SharedScope); |
| 56 | }; |
| 57 | |
| 58 | class ExclusiveScope { |
| 59 | public: |
| 60 | explicit ExclusiveScope(SharedExclusiveLock* lock) : lock_(lock) { |
| 61 | lock_->LockExclusive(); |
| 62 | } |
| 63 | |
| 64 | ~ExclusiveScope() { |
| 65 | lock_->UnlockExclusive(); |
| 66 | } |
| 67 | |
| 68 | private: |
| 69 | SharedExclusiveLock* lock_; |
| 70 | |
| 71 | DISALLOW_COPY_AND_ASSIGN(ExclusiveScope); |
| 72 | }; |
| 73 | |
| 74 | } // namespace rtc |
| 75 | |
| 76 | #endif // WEBRTC_BASE_SHAREDEXCLUSIVELOCK_H_ |