You.i Engine
YiSpinLock.h
Go to the documentation of this file.
1 // © You i Labs Inc. 2000-2017. All rights reserved.
2 #ifndef _YI_SPINLOCK_H_
3 #define _YI_SPINLOCK_H_
4 
5 #include "framework/YiPredef.h"
6 
7 #include <atomic>
8 #include <thread>
9 
10 #ifndef YI_SPINLOCK_ATTEMPTS_BEFORE_YIELD
11 #define YI_SPINLOCK_ATTEMPTS_BEFORE_YIELD 10000
12 #endif
13 
66 {
67 public:
68  CYISpinLock();
69 
75  bool Lock();
76 
83  bool TryLock();
84 
88  bool Unlock();
89 
90 private:
91 #if defined(_MSC_VER) && _MSC_VER <= 1800 // VS2013 or older. Non-static data member initializer is not implemented, and will be done in the constructor instead.
92  std::atomic_flag m_lock;
93 #else
94  std::atomic_flag m_lock = ATOMIC_FLAG_INIT;
95 #endif
96 
98 };
99 
103 {
104 #if defined(_MSC_VER) && _MSC_VER <= 1800 // VS2013 or older. GCC and Clang atomic_flag implementations do not allow operator=.
105  m_lock.clear();
106 #endif
107 }
108 
109 inline bool CYISpinLock::Lock()
110 {
111  while (true)
112  {
113  for (int32_t i = 0; i < YI_SPINLOCK_ATTEMPTS_BEFORE_YIELD; ++i)
114  {
115  if (!m_lock.test_and_set(std::memory_order_acquire))
116  {
117  return true; // Lock acquired.
118  }
119  }
120  std::this_thread::yield();
121  }
122 }
123 
124 inline bool CYISpinLock::TryLock()
125 {
126  return !m_lock.test_and_set(std::memory_order_acquire);
127 }
128 
129 inline bool CYISpinLock::Unlock()
130 {
131  m_lock.clear(std::memory_order_release);
132  return true;
133 }
134 
135 #endif /* _YI_SPINLOCK_H_ */
bool TryLock()
Definition: YiSpinLock.h:124
#define YI_DISALLOW_COPY_AND_ASSIGN(TypeName)
Delete the copy constructor and assignment operator (and consequently the move constructor as well) ...
Definition: YiPredef.h:114
bool Unlock()
Definition: YiSpinLock.h:129
Provides access serialization between threads, where a thread trying to acquire the lock waits in a l...
Definition: YiSpinLock.h:65
CYISpinLock()
Definition: YiSpinLock.h:102
bool Lock()
Definition: YiSpinLock.h:109
#define YI_SPINLOCK_ATTEMPTS_BEFORE_YIELD
Definition: YiSpinLock.h:11