1526fd984Sopenharmony_ci/* 2526fd984Sopenharmony_ci * Copyright (c) 2022 Huawei Device Co., Ltd. 3526fd984Sopenharmony_ci * Licensed under the Apache License, Version 2.0 (the "License"); 4526fd984Sopenharmony_ci * you may not use this file except in compliance with the License. 5526fd984Sopenharmony_ci * You may obtain a copy of the License at 6526fd984Sopenharmony_ci * 7526fd984Sopenharmony_ci * http://www.apache.org/licenses/LICENSE-2.0 8526fd984Sopenharmony_ci * 9526fd984Sopenharmony_ci * Unless required by applicable law or agreed to in writing, software 10526fd984Sopenharmony_ci * distributed under the License is distributed on an "AS IS" BASIS, 11526fd984Sopenharmony_ci * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12526fd984Sopenharmony_ci * See the License for the specific language governing permissions and 13526fd984Sopenharmony_ci * limitations under the License. 14526fd984Sopenharmony_ci */ 15526fd984Sopenharmony_ci 16526fd984Sopenharmony_ci#include "hks_mutex.h" 17526fd984Sopenharmony_ci 18526fd984Sopenharmony_ci#include <pthread.h> 19526fd984Sopenharmony_ci#include <stddef.h> 20526fd984Sopenharmony_ci 21526fd984Sopenharmony_ci#include "hks_mem.h" 22526fd984Sopenharmony_ci#include "hks_template.h" 23526fd984Sopenharmony_ci 24526fd984Sopenharmony_cistruct HksMutex { 25526fd984Sopenharmony_ci pthread_mutex_t mutex; 26526fd984Sopenharmony_ci}; 27526fd984Sopenharmony_ci 28526fd984Sopenharmony_ciHksMutex *HksMutexCreate(void) 29526fd984Sopenharmony_ci{ 30526fd984Sopenharmony_ci HksMutex *mutex = (HksMutex *)HksMalloc(sizeof(HksMutex)); 31526fd984Sopenharmony_ci if (mutex != NULL) { 32526fd984Sopenharmony_ci int result = pthread_mutex_init(&mutex->mutex, NULL); 33526fd984Sopenharmony_ci if (result != 0) { 34526fd984Sopenharmony_ci HKS_FREE(mutex); 35526fd984Sopenharmony_ci mutex = NULL; 36526fd984Sopenharmony_ci } 37526fd984Sopenharmony_ci } 38526fd984Sopenharmony_ci return mutex; 39526fd984Sopenharmony_ci} 40526fd984Sopenharmony_ci 41526fd984Sopenharmony_ciint32_t HksMutexLock(HksMutex *mutex) 42526fd984Sopenharmony_ci{ 43526fd984Sopenharmony_ci HKS_IF_NULL_RETURN(mutex, 1) 44526fd984Sopenharmony_ci 45526fd984Sopenharmony_ci return pthread_mutex_lock(&mutex->mutex); 46526fd984Sopenharmony_ci} 47526fd984Sopenharmony_ci 48526fd984Sopenharmony_ciint32_t HksMutexUnlock(HksMutex *mutex) 49526fd984Sopenharmony_ci{ 50526fd984Sopenharmony_ci HKS_IF_NULL_RETURN(mutex, 1) 51526fd984Sopenharmony_ci 52526fd984Sopenharmony_ci return pthread_mutex_unlock(&mutex->mutex); 53526fd984Sopenharmony_ci} 54526fd984Sopenharmony_ci 55526fd984Sopenharmony_civoid HksMutexClose(HksMutex *mutex) 56526fd984Sopenharmony_ci{ 57526fd984Sopenharmony_ci if (mutex == NULL) { 58526fd984Sopenharmony_ci return; 59526fd984Sopenharmony_ci } 60526fd984Sopenharmony_ci 61526fd984Sopenharmony_ci pthread_mutex_destroy(&mutex->mutex); 62526fd984Sopenharmony_ci HKS_FREE(mutex); 63526fd984Sopenharmony_ci} 64