• 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 "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 }
32 
~Mutex()33 Mutex::~Mutex()
34 {
35     if (created_) {
36         pthread_mutex_destroy(&nativeHandle_);
37     }
38 }
39 
Lock()40 void Mutex::Lock()
41 {
42     if (!created_) {
43         MEDIA_LOG_E("Lock uninitialized pthread mutex!");
44         return;
45     }
46     pthread_mutex_lock(&nativeHandle_);
47 }
48 
TryLock()49 bool Mutex::TryLock()
50 {
51     if (!created_) {
52         MEDIA_LOG_E("TryLock uninitialized pthread mutex.");
53         return false;
54     }
55     int ret = pthread_mutex_trylock(&nativeHandle_);
56     if (ret != 0) {
57         MEDIA_LOG_E("TryLock failed with ret = " PUBLIC_LOG_D32, ret);
58     }
59     return ret == 0;
60 }
61 
Unlock()62 void Mutex::Unlock()
63 {
64     if (!created_) {
65         MEDIA_LOG_E("Unlock uninitialized pthread mutex!");
66         return;
67     }
68     pthread_mutex_unlock(&nativeHandle_);
69 }
70 } // namespace OSAL
71 } // namespace Media
72 } // namespace OHOS