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 OHOS { 22 namespace Media { Mutex()23Mutex::Mutex() : created_(true) 24 { 25 int rtv = pthread_mutex_init(&nativeHandle_, nullptr); 26 if (rtv != 0) { 27 created_ = false; 28 MEDIA_LOG_E("failed to init pthread mutex"); 29 } 30 } 31 ~Mutex()32Mutex::~Mutex() 33 { 34 if (created_) { 35 pthread_mutex_destroy(&nativeHandle_); 36 } 37 } 38 lock()39void Mutex::lock() 40 { 41 if (!created_) { 42 MEDIA_LOG_E("lock uninitialized pthread mutex!"); 43 return; 44 } 45 pthread_mutex_lock(&nativeHandle_); 46 } 47 try_lock()48bool Mutex::try_lock() 49 { 50 if (!created_) { 51 MEDIA_LOG_E("trylock uninitialized pthread mutex."); 52 return false; 53 } 54 int ret = pthread_mutex_trylock(&nativeHandle_); 55 if (ret != 0) { 56 MEDIA_LOG_E("trylock failed with ret = " PUBLIC_LOG_D32, ret); 57 } 58 return ret == 0; 59 } 60 unlock()61void Mutex::unlock() 62 { 63 if (!created_) { 64 MEDIA_LOG_E("unlock uninitialized pthread mutex!"); 65 return; 66 } 67 pthread_mutex_unlock(&nativeHandle_); 68 } 69 } // namespace Media 70 } // namespace OHOS