-
Notifications
You must be signed in to change notification settings - Fork 3
/
SpinLock.h
52 lines (43 loc) · 1.08 KB
/
SpinLock.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
#ifdef __APPLE__
#include <errno.h>
#ifndef PTHREAD_SPIN_LOCK_SHIM
#define PTHREAD_SPIN_LOCK_SHIM
typedef int pthread_spinlock_t;
#ifndef PTHREAD_PROCESS_SHARED
# define PTHREAD_PROCESS_SHARED 1
#endif
#ifndef PTHREAD_PROCESS_PRIVATE
# define PTHREAD_PROCESS_PRIVATE 2
#endif
static inline int pthread_spin_init(pthread_spinlock_t *lock, int pshared) {
__asm__ __volatile__ ("" ::: "memory");
*lock = 0;
return 0;
}
static inline int pthread_spin_destroy(pthread_spinlock_t *lock) {
return 0;
}
static inline int pthread_spin_lock(pthread_spinlock_t *lock) {
while (1) {
int i;
for (i=0; i < 10000; i++) {
if (__sync_bool_compare_and_swap(lock, 0, 1)) {
return 0;
}
}
sched_yield();
}
}
static inline int pthread_spin_trylock(pthread_spinlock_t *lock) {
if (__sync_bool_compare_and_swap(lock, 0, 1)) {
return 0;
}
return EBUSY;
}
static inline int pthread_spin_unlock(pthread_spinlock_t *lock) {
__asm__ __volatile__ ("" ::: "memory");
*lock = 0;
return 0;
}
#endif
#endif