-
Notifications
You must be signed in to change notification settings - Fork 2
/
mutex_pthread.c
50 lines (45 loc) · 1.03 KB
/
mutex_pthread.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct mutex_s {
pthread_mutex_t handle;
} mutex_s;
bool mutex_lock(void *ctx) {
mutex_s *mutex = (mutex_s *)ctx;
if (!mutex || pthread_mutex_lock(&mutex->handle))
return false;
return true;
}
bool mutex_unlock(void *ctx) {
mutex_s *mutex = (mutex_s *)ctx;
if (!mutex || pthread_mutex_unlock(&mutex->handle))
return false;
return true;
}
void *mutex_create(void) {
mutex_s *mutex = (mutex_s *)calloc(1, sizeof(mutex_s));
if (!mutex)
return NULL;
if (pthread_mutex_init(&mutex->handle, NULL)) {
free(mutex);
return NULL;
}
return mutex;
}
bool mutex_delete(void **ctx) {
if (!ctx)
return false;
mutex_s *mutex = (mutex_s *)*ctx;
if (!mutex)
return false;
if (pthread_mutex_destroy(&mutex->handle)) {
free(mutex);
*ctx = NULL;
return false;
}
free(mutex);
*ctx = NULL;
return true;
}