• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 #ifndef SEC_UTILS_COMMON_MUTEX_H
17 #define SEC_UTILS_COMMON_MUTEX_H
18 
19 #include <pthread.h>
20 
21 #include "utils_log.h"
22 
23 #define MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
24 #define RECURSIVE_MUTEX_INITIALIZER PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
25 
26 #define INITED_MUTEX      \
27     {                     \
28         MUTEX_INITIALIZER \
29     }
30 
31 #define IRECURSIVE_INITED_MUTEX                \
32     {                                          \
33         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \
34     }
35 
36 #ifdef __cplusplus
37 extern "C" {
38 #endif
39 
40 typedef struct Mutex {
41     pthread_mutex_t mutex;
42 } Mutex;
43 
InitMutex(Mutex * mutex)44 inline static void InitMutex(Mutex *mutex)
45 {
46     int ret = pthread_mutex_init(&mutex->mutex, NULL);
47     if (ret != 0) {
48         SECURITY_LOG_ERROR("InitMutex pthread_mutex_init error");
49     }
50 }
51 
InitRecursiveMutex(Mutex * mutex)52 inline static void InitRecursiveMutex(Mutex *mutex)
53 {
54     pthread_mutexattr_t attr;
55     pthread_mutexattr_init(&attr);
56     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
57     int ret = pthread_mutex_init(&mutex->mutex, &attr);
58     if (ret != 0) {
59         SECURITY_LOG_ERROR("InitRecursiveMutex pthread_mutex_init error");
60     }
61 }
62 
LockMutex(Mutex * mutex)63 inline static void LockMutex(Mutex *mutex)
64 {
65     int ret = pthread_mutex_lock(&(mutex->mutex));
66     if (ret != 0) {
67         SECURITY_LOG_ERROR("LockMutex pthread_mutex_lock error");
68     }
69 }
70 
UnlockMutex(Mutex * mutex)71 inline static void UnlockMutex(Mutex *mutex)
72 {
73     int ret = pthread_mutex_unlock(&(mutex->mutex));
74     if (ret != 0) {
75         SECURITY_LOG_ERROR("UnlockMutex pthread_mutex_unlock error");
76     }
77 }
78 
79 #ifdef __cplusplus
80 }
81 #endif
82 
83 #endif // SEC_UTILS_COMMON_MUTEX_H
84