1 /*
2 * Copyright (c) 2021-2023 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 "Mutex"
17
18 #include "osal/task/mutex.h"
19 #include "common/log.h"
20
21 namespace {
22 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_FOUNDATION, "Mutex" };
23 }
24
25 namespace OHOS {
26 namespace Media {
Mutex()27 Mutex::Mutex() : created_(true)
28 {
29 int rtv = pthread_mutex_init(&nativeHandle_, nullptr);
30 if (rtv != 0) {
31 created_ = false;
32 MEDIA_LOG_E("failed to init pthread mutex");
33 }
34 }
35
~Mutex()36 Mutex::~Mutex()
37 {
38 if (created_) {
39 pthread_mutex_destroy(&nativeHandle_);
40 }
41 }
42
lock()43 void Mutex::lock()
44 {
45 FALSE_RETURN_MSG(created_, "lock uninitialized pthread mutex!");
46 pthread_mutex_lock(&nativeHandle_);
47 }
48
try_lock()49 bool Mutex::try_lock()
50 {
51 FALSE_RETURN_V_MSG_E(created_,
52 false, "trylock uninitialized pthread mutex.");
53 int ret = pthread_mutex_trylock(&nativeHandle_);
54 FALSE_LOG_MSG(ret == 0, "trylock failed with ret = " PUBLIC_LOG_D32, ret);
55 return ret == 0;
56 }
57
unlock()58 void Mutex::unlock()
59 {
60 FALSE_RETURN_MSG(created_, "unlock uninitialized pthread mutex!");
61 pthread_mutex_unlock(&nativeHandle_);
62 }
63
FairMutex()64 FairMutex::FairMutex() : Mutex()
65 {
66 int rtv = pthread_mutex_init(&failLockHandle_, nullptr);
67 if (rtv != 0) {
68 created_ = false;
69 MEDIA_LOG_E("failed to init FairMutex");
70 } else {
71 created_ = true;
72 }
73 }
74
~FairMutex()75 FairMutex::~FairMutex()
76 {
77 if (created_) {
78 pthread_mutex_destroy(&failLockHandle_);
79 }
80 }
81
lock()82 void FairMutex::lock()
83 {
84 if (created_) {
85 pthread_mutex_lock(&failLockHandle_);
86 Mutex::lock();
87 pthread_mutex_unlock(&failLockHandle_);
88 } else {
89 Mutex::lock();
90 }
91 }
92 } // namespace Media
93 } // namespace OHOS