TDME2  1.9.200
SpinLock.h
Go to the documentation of this file.
1 #pragma once
2 
4 
5 #include <tdme/tdme.h>
6 
7 #include <atomic>
8 #include <string>
9 
10 using std::atomic_flag;
11 using std::string;
12 
13 /**
14  * Spin Lock implementation.
15  * @author Andreas Drewke
16  */
18 public:
19  // forbid class copy
21 
22  /**
23  * @brief Public constructor
24  * @param name name
25  */
26  inline SpinLock(const string& name): name(name) {}
27 
28  /**
29  * @brief Destroys the spin lock
30  */
31  inline ~SpinLock() {}
32 
33  /**
34  * @brief Tries to locks the spin lock
35  */
36  inline bool tryLock() {
37  if (locked.test_and_set(std::memory_order_acquire) == false) return true;
38  return false;
39  }
40 
41  /**
42  * @brief Locks the spin lock, additionally spin lock locks will block until other locks have been unlocked.
43  */
44  inline void lock() {
45  while (locked.test_and_set(std::memory_order_acquire));
46  }
47 
48  /**
49  * @brief Unlocks this spin lock
50  */
51  inline void unlock() {
52  locked.clear(std::memory_order_release);
53  }
54 
55 private:
56  string name;
57  atomic_flag locked = ATOMIC_FLAG_INIT;
58 };
Spin Lock implementation.
Definition: SpinLock.h:17
~SpinLock()
Destroys the spin lock.
Definition: SpinLock.h:31
void unlock()
Unlocks this spin lock.
Definition: SpinLock.h:51
void lock()
Locks the spin lock, additionally spin lock locks will block until other locks have been unlocked.
Definition: SpinLock.h:44
bool tryLock()
Tries to locks the spin lock.
Definition: SpinLock.h:36
#define FORBID_CLASS_COPY(CLASS)
Definition: tdme.h:6