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 "Mutex"
17 
18 #include "foundation/osal/thread/mutex.h"
19 #include "foundation/log.h"
20 
21 namespace OHOS {
22 namespace Media {
23 namespace OSAL {
Mutex()24 Mutex::Mutex() : created_(true)
25 {
26     int rtv = pthread_mutex_init(&nativeHandle_, nullptr);
27     if (rtv != 0) {
28         created_ = false;
29         MEDIA_LOG_E("failed to init pthread mutex");
30     }
31     MEDIA_LOG_D("succeed to init pthread mutex");
32 }
33 
~Mutex()34 Mutex::~Mutex()
35 {
36     if (created_) {
37         pthread_mutex_destroy(&nativeHandle_);
38         MEDIA_LOG_D("succeed to destroy pthread mutex");
39     }
40 }
41 
Lock()42 void Mutex::Lock()
43 {
44     if (!created_) {
45         MEDIA_LOG_E("Lock uninitialized pthread mutex!");
46         return;
47     }
48     pthread_mutex_lock(&nativeHandle_);
49     MEDIA_LOG_D("Lock pthread mutex done!");
50 }
51 
TryLock()52 bool Mutex::TryLock()
53 {
54     if (!created_) {
55         MEDIA_LOG_E("TryLock uninitialized pthread mutex.");
56         return false;
57     }
58     int ret = pthread_mutex_trylock(&nativeHandle_);
59     if (ret != 0) {
60         MEDIA_LOG_E("TryLock failed with ret = " PUBLIC_LOG_D32, ret);
61     }
62     return ret == 0;
63 }
64 
Unlock()65 void Mutex::Unlock()
66 {
67     if (!created_) {
68         MEDIA_LOG_E("Unlock uninitialized pthread mutex!");
69         return;
70     }
71     pthread_mutex_unlock(&nativeHandle_);
72 }
73 } // namespace OSAL
74 } // namespace Media
75 } // namespace OHOS