spinlock.hpp
Go to the documentation of this file.
1 #ifndef SPINLOCK_HPP
2 #define SPINLOCK_HPP
3 
4 #include <atomic>
5 
6 class __attribute__((aligned(64))) SpinLock {
7 private:
8  std::atomic_flag latch = ATOMIC_FLAG_INIT;
9 
10 public:
11  SpinLock(){};
12 
13  bool trylock() { return !latch.test_and_set(std::memory_order::memory_order_acquire); }
14 
15  void lock() {
16  while (!trylock()) {
17  __asm__("pause;");
18  }
19  };
20 
21  void unlock() { latch.clear(std::memory_order::memory_order_release); }
22 };
23 
25 private:
26  // The useful part
27  std::atomic_flag latch = ATOMIC_FLAG_INIT;
28 
29  // The padding, assumes 64 byte cacheline
30  // This should prevent false sharing
31  volatile char c[64 - sizeof(std::atomic_flag)];
32 
33 public:
35  // This cast is just to silence clang
36  (void)c;
37  };
38 
39  bool trylock() { return !latch.test_and_set(std::memory_order::memory_order_acquire); }
40 
41  void lock() {
42  while (!trylock()) {
43  __asm__("pause;");
44  }
45  };
46 
47  void unlock() { latch.clear(std::memory_order::memory_order_release); }
48 };
49 
50 #endif /* SPINLOCK_HPP */
SpinLock()
Definition: spinlock.hpp:11
void unlock()
Definition: spinlock.hpp:21
bool trylock()
Definition: spinlock.hpp:13
void lock()
Definition: spinlock.hpp:15
void unlock()
Definition: spinlock.hpp:47
bool trylock()
Definition: spinlock.hpp:39