• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #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     (void)pthread_mutex_init(&mutex->mutex, NULL);
47 }
48 
InitRecursiveMutex(Mutex * mutex)49 inline static void InitRecursiveMutex(Mutex *mutex)
50 {
51     pthread_mutexattr_t attr;
52     pthread_mutexattr_init(&attr);
53     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
54     (void)pthread_mutex_init(&mutex->mutex, &attr);
55 }
56 
LockMutex(Mutex * mutex)57 inline static void LockMutex(Mutex *mutex)
58 {
59     int ret = pthread_mutex_lock(&(mutex->mutex));
60     if (ret != 0) {
61         SECURITY_LOG_ERROR("pthread_mutex_lock error");
62     }
63 }
64 
UnlockMutex(Mutex * mutex)65 inline static void UnlockMutex(Mutex *mutex)
66 {
67     int ret = pthread_mutex_unlock(&(mutex->mutex));
68     if (ret != 0) {
69         SECURITY_LOG_ERROR("pthread_mutex_unlock error");
70     }
71 }
72 
73 #ifdef __cplusplus
74 }
75 #endif
76 
77 #endif // SEC_UTILS_COMMON_MUTEX_H
78