add Makefile and instructions to run programs
[c11concurrency-benchmarks.git] / silo / spinlock.h
1 #ifndef _SPINLOCK_H_
2 #define _SPINLOCK_H_
3
4 #include <stdint.h>
5
6 #include "amd64.h"
7 #include "macros.h"
8 #include "util.h"
9
10 class spinlock {
11 public:
12   spinlock() : value(0) {}
13
14   spinlock(const spinlock &) = delete;
15   spinlock(spinlock &&) = delete;
16   spinlock &operator=(const spinlock &) = delete;
17
18   inline void
19   lock()
20   {
21     // XXX: implement SPINLOCK_BACKOFF
22     uint32_t v = value;
23     while (v || !__sync_bool_compare_and_swap(&value, 0, 1)) {
24       nop_pause();
25       v = value;
26     }
27     COMPILER_MEMORY_FENCE;
28   }
29
30   inline bool
31   try_lock()
32   {
33     return __sync_bool_compare_and_swap(&value, 0, 1);
34   }
35
36   inline void
37   unlock()
38   {
39     INVARIANT(value);
40     value = 0;
41     COMPILER_MEMORY_FENCE;
42   }
43
44   // just for debugging
45   inline bool
46   is_locked() const
47   {
48     return value;
49   }
50
51 private:
52   volatile uint32_t value;
53 };
54
55 #endif /* _SPINLOCK_H_ */