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 #include "platform/lock/include/rw_lock.h"
17 
18 namespace OHOS {
19 namespace AI {
RwLock()20 RwLock::RwLock()
21     : readCnt_(0), writeCnt_(0), writeFlag_(false)
22 {
23 }
24 
25 RwLock::~RwLock() = default;
26 
LockRead()27 void RwLock::LockRead()
28 {
29     std::unique_lock<std::mutex> guard(mutex_);
30     condRead_.wait(guard, [=]()->bool { return writeCnt_ == 0; });
31     ++readCnt_;
32 }
33 
LockWrite()34 void RwLock::LockWrite()
35 {
36     std::unique_lock<std::mutex> guard(mutex_);
37     ++writeCnt_;
38     condWrite_.wait(guard, [=]()->bool { return (readCnt_ == 0) && (!writeFlag_); });
39     writeFlag_ = true;
40 }
41 
UnLockRead()42 void RwLock::UnLockRead()
43 {
44     std::unique_lock<std::mutex> guard(mutex_);
45     if ((--readCnt_ == 0) && (writeCnt_ > 0)) {
46         condWrite_.notify_one();
47     }
48 }
49 
UnLockWrite()50 void RwLock::UnLockWrite()
51 {
52     std::unique_lock<std::mutex> guard(mutex_);
53     if (--writeCnt_ == 0) {
54         condRead_.notify_all();
55     } else {
56         condWrite_.notify_one();
57     }
58 
59     writeFlag_ = false;
60 }
61 } // namespace AI
62 } // namespace OHOS
63