-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmutex.h
88 lines (76 loc) · 1.68 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
#ifndef _CILK_MUTEX_H
#define _CILK_MUTEX_H
// Forward declaration
typedef union cilk_mutex cilk_mutex;
// Includes
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "rts-config.h"
#ifndef __APPLE__
#define USE_SPINLOCK 1
#endif
#if USE_SPINLOCK
union cilk_mutex {
volatile int memory;
pthread_spinlock_t posix;
};
#else
union cilk_mutex {
volatile int memory;
pthread_mutex_t posix;
};
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wthread-safety-analysis"
static inline void cilk_mutex_init(cilk_mutex *lock) {
#if USE_SPINLOCK
int ret = pthread_spin_init(&(lock->posix), PTHREAD_PROCESS_PRIVATE);
if (ret != 0) {
errno = ret;
perror("Pthread_spin_init failed");
exit(-1);
}
#else
pthread_mutex_init(&(lock->posix), NULL);
#endif
}
static inline void cilk_mutex_lock(cilk_mutex *lock) {
#if USE_SPINLOCK
pthread_spin_lock(&(lock->posix));
#else
pthread_mutex_lock(&(lock->posix));
#endif
}
static inline void cilk_mutex_unlock(cilk_mutex *lock) {
#if USE_SPINLOCK
pthread_spin_unlock(&(lock->posix));
#else
pthread_mutex_unlock(&(lock->posix));
#endif
}
static inline int cilk_mutex_try(cilk_mutex *lock) {
#if USE_SPINLOCK
if (pthread_spin_trylock(&(lock->posix)) == 0) {
return 1;
} else {
return 0;
}
#else
if (pthread_mutex_trylock(&(lock->posix)) == 0) {
return 1;
} else {
return 0;
}
#endif
}
#pragma clang diagnostic pop
static inline void cilk_mutex_destroy(cilk_mutex *lock) {
#if USE_SPINLOCK
pthread_spin_destroy(&(lock->posix));
#else
pthread_mutex_destroy(&(lock->posix));
#endif
}
#endif