/
mutex.c
116 lines (91 loc) · 1.69 KB
/
mutex.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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* mutex.c
* bouncingbots
*
* Created by David Reed on 10/12/12.
* Copyright 2012 David Reed. All rights reserved.
*
*/
#include "mutex.h"
#ifdef WINDOWS
#include <windows.h>
#else
#include <pthread.h>
#endif
#ifdef WINDOWS
struct _bb_mutex {
HANDLE m;
};
bb_mutex bb_mutex_create()
{
bb_mutex m = malloc(sizeof(struct _bb_mutex));
if (m != NULL) {
m->m = CreateMutex(NULL, BB_FALSE, NULL);
if (m->m == NULL) {
free(m);
m = NULL;
}
}
return m;
}
void bb_mutex_dealloc(bb_mutex mutex)
{
CloseHandle(mutex->m);
free(mutex);
}
bb_bool bb_mutex_lock(bb_mutex mutex)
{
return WaitForSingleObject(mutex->m, INFINITE) == WAIT_OBJECT_0;
}
bb_bool bb_mutex_try_lock(bb_mutex mutex)
{
return WaitForSingleObject(mutex->m, 0) == WAIT_OBJECT_0;
}
void bb_mutex_unlock(bb_mutex mutex)
{
ReleaseMutex(mutex->m);
}
#else
#include <stdlib.h>
#include <pthread.h>
/* We will assume for the time being that anything that isn't Windows supports pthread mutexes */
struct _bb_mutex {
pthread_mutex_t *m;
};
bb_mutex bb_mutex_create()
{
bb_mutex m = malloc(sizeof(struct _bb_mutex));
if (m != NULL) {
m->m = malloc(sizeof(pthread_mutex_t));
if (m->m != NULL) {
if (pthread_mutex_init(m->m, NULL) != 0) {
free(m->m);
free(m);
m = NULL;
}
} else {
free(m);
m = NULL;
}
}
return m;
}
void bb_mutex_dealloc(bb_mutex mutex)
{
pthread_mutex_destroy(mutex->m);
free(mutex->m);
free(mutex);
}
bb_bool bb_mutex_lock(bb_mutex mutex)
{
return pthread_mutex_lock(mutex->m) == 0;
}
bb_bool bb_mutex_try_lock(bb_mutex mutex)
{
return pthread_mutex_trylock(mutex->m) == 0;
}
void bb_mutex_unlock(bb_mutex mutex)
{
pthread_mutex_unlock(mutex->m);
}
#endif