• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 #define HST_LOG_TAG "ScopedLock"
17 
18 #include "scoped_lock.h"
19 
20 #include <utility>
21 
22 namespace OHOS {
23 namespace Media {
24 namespace OSAL {
ScopedLock()25 ScopedLock::ScopedLock() : mutex_(nullptr)
26 {
27 }
28 
ScopedLock(Mutex & mutex)29 ScopedLock::ScopedLock(Mutex& mutex) : mutex_(&mutex)
30 {
31     mutex_->Lock();
32 }
33 
~ScopedLock()34 ScopedLock::~ScopedLock()
35 {
36     if (mutex_ != nullptr) {
37         mutex_->Unlock();
38         mutex_ = nullptr;
39     }
40 }
41 
ScopedLock(ScopedLock && other)42 ScopedLock::ScopedLock(ScopedLock&& other) noexcept
43 {
44     mutex_ = nullptr;
45     *this = std::move(other);
46 }
47 
operator =(ScopedLock && other)48 ScopedLock& ScopedLock::operator=(ScopedLock&& other) noexcept
49 {
50     if (this != &other) {
51         if (mutex_) {
52             mutex_->Unlock();
53         }
54         mutex_ = other.mutex_;
55         other.mutex_ = nullptr;
56     }
57     return *this;
58 }
59 
Lock()60 void ScopedLock::Lock()
61 {
62     if (mutex_ != nullptr) {
63         mutex_->Lock();
64     }
65 }
66 
TryLock()67 bool ScopedLock::TryLock()
68 {
69     bool ret = false;
70     if (mutex_ != nullptr) {
71         ret = mutex_->TryLock();
72     }
73     return ret;
74 }
75 
Unlock()76 void ScopedLock::Unlock()
77 {
78     if (mutex_ != nullptr) {
79         mutex_->Unlock();
80     }
81 }
82 } // namespace OSAL
83 } // namespace Media
84 } // namespace OHOS