1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef RW_LOCK_H 17 #define RW_LOCK_H 18 19 #include <condition_variable> 20 #include <mutex> 21 22 #include "utils/aie_macros.h" 23 #include "utils/constants/constants.h" 24 25 namespace OHOS { 26 namespace AI { 27 class RwLock { 28 FORBID_COPY_AND_ASSIGN(RwLock); 29 public: 30 RwLock(); 31 ~RwLock(); 32 33 public: 34 /** 35 * Lock the reading operation. 36 */ 37 void LockRead(); 38 39 /** 40 * Lock the writing operation. 41 */ 42 void LockWrite(); 43 44 /** 45 * Unlock the reading operation. 46 */ 47 void UnLockRead(); 48 49 /** 50 * Unlock the writing operation. 51 */ 52 void UnLockWrite(); 53 54 private: 55 // Count of reading operations. 56 volatile size_t readCnt_; 57 58 // Count of writing operations. 59 volatile size_t writeCnt_; 60 61 // The flag of writing operations. 62 volatile bool writeFlag_; 63 64 std::mutex mutex_; 65 std::condition_variable condWrite_; 66 std::condition_variable condRead_; 67 }; 68 69 template<typename RwLockable> 70 class WriteGuard { 71 FORBID_COPY_AND_ASSIGN(WriteGuard); 72 public: 73 /** 74 * Lock to guard the writing operation. 75 * 76 * @param rwLockable the lock with {@code RwLock} base type. 77 */ 78 explicit WriteGuard(RwLockable &rwLockable); 79 80 /** 81 * Unlock the guarding of writing operation. 82 */ 83 ~WriteGuard(); 84 85 private: 86 RwLockable& rwLockable_; 87 }; 88 89 template<typename RwLockable> 90 class ReadGuard { 91 FORBID_COPY_AND_ASSIGN(ReadGuard); 92 public: 93 /** 94 * Lock to guard the reading operation. 95 * 96 * @param rwLockable the lock with {@code RwLock} base type. 97 */ 98 explicit ReadGuard(RwLockable &rwLockable); 99 100 /** 101 * Unlock the guarding of reading operation. 102 */ 103 ~ReadGuard(); 104 105 private: 106 RwLockable& rwLockable_; 107 }; 108 } // namespace AI 109 } // namespace OHOS 110 111 // Include the implementation of reader-writer lock. 112 #include "platform/lock/include/rw_lock.inl" 113 114 #endif // RW_LOCK_H