• 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 #include "platform/include/mutex.h"
17 #include <stdlib.h>
18 #include <pthread.h>
19 #include "platform/include/platform_def.h"
20 
21 typedef struct Mutex {
22     pthread_mutex_t mutex;
23 } MutexInternal;
24 
MutexCreate()25 Mutex *MutexCreate()
26 {
27     Mutex *mutex = (Mutex *)malloc(sizeof(Mutex));
28     pthread_mutexattr_t attr = {0};
29     pthread_mutexattr_init(&attr);
30 
31     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
32     if (mutex != NULL) {
33         if (pthread_mutex_init(&mutex->mutex, &attr) != 0) {
34             free(mutex);
35             return NULL;
36         }
37     }
38     return mutex;
39 }
40 
MutexDelete(Mutex * mutex)41 void MutexDelete(Mutex *mutex)
42 {
43     if (mutex == NULL) {
44         return;
45     }
46 
47     pthread_mutex_destroy(&mutex->mutex);
48     free(mutex);
49 }
50 
MutexLock(Mutex * mutex)51 void MutexLock(Mutex *mutex)
52 {
53     ASSERT(mutex);
54     pthread_mutex_lock(&mutex->mutex);
55 }
56 
MutexUnlock(Mutex * mutex)57 void MutexUnlock(Mutex *mutex)
58 {
59     ASSERT(mutex);
60     pthread_mutex_unlock(&mutex->mutex);
61 }
62 
MutexTryLock(Mutex * mutex)63 int32_t MutexTryLock(Mutex *mutex)
64 {
65     ASSERT(mutex);
66     if (pthread_mutex_trylock(&mutex->mutex) != 0) {
67         return -1;
68     }
69     return 0;
70 }