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