MP-Gadget  5.0.1.dev1-76bc7d4726-dirty
spinlocks.c
Go to the documentation of this file.
1 #include "spinlocks.h"
2 #include "mymalloc.h"
3 
4 #ifndef NO_OPENMP_SPINLOCK
5 #include <pthread.h>
6 #else
7 #include <omp.h>
8 #endif
9 
10 /* Temporary array for spinlocks*/
11 struct SpinLocks
12 {
13 #ifndef NO_OPENMP_SPINLOCK
14  pthread_spinlock_t * SpinLocks;
15 #else
16  omp_lock_t * SpinLocks;
17 #endif
19 };
20 
21 static struct SpinLocks spin;
22 
23 void lock_spinlock(int i, struct SpinLocks * spin) {
24 #ifndef NO_OPENMP_SPINLOCK
25  pthread_spin_lock(&spin->SpinLocks[i]);
26 #else
27  omp_set_lock(&spin->SpinLocks[i]);
28 #endif
29 }
30 void unlock_spinlock(int i, struct SpinLocks * spin) {
31 #ifndef NO_OPENMP_SPINLOCK
32  pthread_spin_unlock(&spin->SpinLocks[i]);
33 #else
34  omp_unset_lock(&spin->SpinLocks[i]);
35 #endif
36 }
37 
38 int try_lock_spinlock(int i, struct SpinLocks * spin)
39 {
40 #ifndef NO_OPENMP_SPINLOCK
41  return pthread_spin_trylock(&spin->SpinLocks[i]);
42 #else
43  /* omp returns true if successful, ie, lock taken.
44  * pthread_spin_lock returns 0 on success*/
45  return !omp_test_lock(&spin->SpinLocks[i]);
46 #endif
47 }
48 
49 struct SpinLocks * init_spinlocks(int NumLock)
50 {
51  int i;
52  /* Initialize the spinlocks*/
53 #ifndef NO_OPENMP_SPINLOCK
54  spin.SpinLocks = (pthread_spinlock_t *) mymalloc("SpinLocks", NumLock * sizeof(pthread_spinlock_t));
55  #pragma omp parallel for
56 #else
57  spin.SpinLocks = mymalloc("SpinLocks", NumLock * sizeof(omp_lock_t));
58 #endif
59  for(i = 0; i < NumLock; i ++) {
60 #ifndef NO_OPENMP_SPINLOCK
61  pthread_spin_init(&spin.SpinLocks[i], PTHREAD_PROCESS_PRIVATE);
62 #else
63  omp_init_lock(&spin.SpinLocks[i]);
64 #endif
65  }
66  spin.NumSpinLock = NumLock;
67  return &spin;
68 }
69 
71 {
72  int i;
73  for(i = 0; i < spin->NumSpinLock; i ++) {
74 #ifndef NO_OPENMP_SPINLOCK
75  pthread_spin_destroy(&(spin->SpinLocks[i]));
76 #else
77  omp_destroy_lock(&(spin->SpinLocks[i]));
78 #endif
79  }
80  myfree((void *) spin->SpinLocks);
81 }
82 
#define mymalloc(name, size)
Definition: mymalloc.h:15
#define myfree(x)
Definition: mymalloc.h:19
void free_spinlocks(struct SpinLocks *spin)
Definition: spinlocks.c:70
int try_lock_spinlock(int i, struct SpinLocks *spin)
Definition: spinlocks.c:38
void lock_spinlock(int i, struct SpinLocks *spin)
Definition: spinlocks.c:23
struct SpinLocks * init_spinlocks(int NumLock)
Definition: spinlocks.c:49
static struct SpinLocks spin
Definition: spinlocks.c:21
void unlock_spinlock(int i, struct SpinLocks *spin)
Definition: spinlocks.c:30
int NumSpinLock
Definition: spinlocks.c:18
pthread_spinlock_t * SpinLocks
Definition: spinlocks.c:14