-
Notifications
You must be signed in to change notification settings - Fork 1
/
mutex.h
95 lines (68 loc) · 1.72 KB
/
mutex.h
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// mutex and rwlock for linux and windows
#ifndef KLIBS_MUTEX_H
#define KLIBS_MUTEX_H
#ifdef _WIN32
#include <windows.h>
typedef HANDLE mutex_t;
static void mutex_create(mutex_t *mutex) {
*mutex = CreateMutexA(NULL, false, NULL);
}
static void mutex_lock(mutex_t *mutex) {
WaitForSingleObject(*mutex, 0);
}
static void mutex_unlock(mutex_t *mutex) {
ReleaseMutex(*mutex);
}
static void mutex_destroy(mutex_t *mutex) {
CloseHandle(*mutex);
}
// TODO: do better
typedef mutex_t rwlock_t;
static void rwlock_create(rwlock_t *rwlock) {
mutex_create(rwlock);
}
static void rwlock_r_lock(rwlock_t *rwlock) {
mutex_lock(rwlock);
}
static void rwlock_w_lock(rwlock_t *rwlock) {
mutex_lock(rwlock);
}
static void rwlock_unlock(rwlock_t *rwlock) {
mutex_unlock(rwlock);
}
static void rwlock_destroy(rwlock_t *rwlock) {
mutex_destroy(rwlock);
}
#else
#include <pthread.h>
typedef pthread_mutex_t mutex_t;
static void mutex_create(mutex_t *mutex) {
pthread_mutex_init(mutex, NULL);
}
static void mutex_lock(mutex_t *mutex) {
pthread_mutex_lock(mutex);
}
static void mutex_unlock(mutex_t *mutex) {
pthread_mutex_unlock(mutex);
}
static void mutex_destroy(mutex_t *mutex) {
pthread_mutex_destroy(mutex);
}
typedef pthread_rwlock_t rwlock_t;
static void rwlock_create(rwlock_t *rwlock) {
pthread_rwlock_init(rwlock, NULL);
}
static void rwlock_r_lock(rwlock_t *rwlock) {
pthread_rwlock_rdlock(rwlock);
}
static void rwlock_w_lock(rwlock_t *rwlock) {
pthread_rwlock_wrlock(rwlock);
}
static void rwlock_unlock(rwlock_t *rwlock) {
pthread_rwlock_unlock(rwlock);
}
static void rwlock_destroy(rwlock_t *rwlock) {
pthread_rwlock_destroy(rwlock);
}
#endif
#endif //KLIBS_MUTEX_H