1 /*
2 * Copyright (c) 2022 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 #include "hks_mutex.h"
17
18 #include <pthread.h>
19 #include <stddef.h>
20
21 #include "hks_log.h"
22 #include "hks_mem.h"
23 #include "hks_template.h"
24
25 struct HksMutex {
26 pthread_mutex_t mutex;
27 };
28
HksMutexCreate(void)29 HksMutex *HksMutexCreate(void)
30 {
31 HksMutex *mutex = (HksMutex *)HksMalloc(sizeof(HksMutex));
32 if (mutex == NULL) {
33 HKS_LOG_E("HksMalloc HksMutex fail");
34 return NULL;
35 }
36 int result = pthread_mutex_init(&mutex->mutex, NULL);
37 if (result != 0) {
38 HKS_LOG_E("pthread_mutex_init fail %" LOG_PUBLIC "d", result);
39 HKS_FREE(mutex);
40 mutex = NULL;
41 }
42 return mutex;
43 }
44
HksMutexLock(HksMutex * mutex)45 int32_t HksMutexLock(HksMutex *mutex)
46 {
47 HKS_IF_NULL_LOGE_RETURN(mutex, HKS_ERROR_NULL_POINTER, "NULL mutex in HksMutexLock")
48
49 int result = pthread_mutex_lock(&mutex->mutex);
50 if (result != 0) {
51 HKS_LOG_E("pthread_mutex_lock fail %" LOG_PUBLIC "d", result);
52 }
53 return result;
54 }
55
HksMutexUnlock(HksMutex * mutex)56 int32_t HksMutexUnlock(HksMutex *mutex)
57 {
58 HKS_IF_NULL_LOGE_RETURN(mutex, HKS_ERROR_NULL_POINTER, "NULL mutex in HksMutexUnlock")
59
60 int result = pthread_mutex_unlock(&mutex->mutex);
61 HKS_IF_TRUE_LOGE(result != 0, "pthread_mutex_unlock fail %" LOG_PUBLIC "d", result)
62 return result;
63 }
64
HksMutexClose(HksMutex * mutex)65 void HksMutexClose(HksMutex *mutex)
66 {
67 if (mutex == NULL) {
68 HKS_LOG_E("NULL mutex in HksMutexClose");
69 return;
70 }
71
72 int result = pthread_mutex_destroy(&mutex->mutex);
73 HKS_IF_TRUE_LOGE(result != 0, "pthread_mutex_destroy fail %" LOG_PUBLIC "d", result)
74 HKS_FREE(mutex);
75 }
76