Banuba SDK
concurrency.hpp
1 #pragma once
2 
3 #include <atomic>
4 
5 namespace bnb
6 {
7  /**
8  * @addtogroup Utils
9  * @{
10  */
11 
12  class spin_lock
13  {
14  public:
15  explicit spin_lock(std::atomic_flag& f)
16  : flag(f)
17  {
18  while (flag.test_and_set(std::memory_order_acquire))
19  ;
20  }
21 
22  ~spin_lock()
23  {
24  flag.clear(std::memory_order_release);
25  }
26 
27  private:
28  std::atomic_flag& flag;
29  };
30 
31  class spin_mutex
32  {
33  public:
34  void lock()
35  {
36  while (flag.test_and_set(std::memory_order_acquire))
37  ;
38  }
39  void unlock()
40  {
41  flag.clear(std::memory_order_release);
42  }
43  bool try_lock()
44  {
45  return !(flag.test_and_set(std::memory_order_acquire));
46  }
47 
48  private:
49  std::atomic_flag flag;
50  };
51 
52  /** @} */ // endgroup utils
53 } // namespace bnb
bnb::spin_mutex
Definition: concurrency.hpp:31
bnb::spin_lock
Definition: concurrency.hpp:12