BitShares-Core  5.0.0
BitShares blockchain implementation and command-line interface software
spin_lock.cpp
Go to the documentation of this file.
2 #include <fc/time.hpp>
3 #include <boost/atomic.hpp>
4 #include <boost/memory_order.hpp>
5 #include <new>
6 
7 namespace fc {
8  #define define_self boost::atomic<int>* self = (boost::atomic<int>*)&_lock
10  {
12  new (self) boost::atomic<int>();
13  static_assert( sizeof(boost::atomic<int>) == sizeof(_lock), "" );
14  self->store(unlocked);
15  }
16 
19  return self->exchange(locked, boost::memory_order_acquire)!=locked;
20  }
21 
23  return try_lock_until( fc::time_point::now() + us );
24  }
25 
26  bool spin_lock::try_lock_until( const fc::time_point& abs_time ) {
27  while( abs_time > time_point::now() ) {
28  if( try_lock() )
29  return true;
30  }
31  return false;
32  }
33 
34  void spin_lock::lock() {
36  while( self->exchange(locked, boost::memory_order_acquire)==locked) { }
37  }
38 
41  self->store(unlocked, boost::memory_order_release);
42  }
43 
44  #undef define_self
45 
46 } // namespace fc
bool try_lock()
Definition: spin_lock.cpp:17
#define define_self
Definition: spin_lock.cpp:8
void unlock()
Definition: spin_lock.cpp:39
bool try_lock_until(const time_point &abs_time)
Definition: spin_lock.cpp:26
bool try_lock_for(const microseconds &rel_time)
Definition: spin_lock.cpp:22
Definition: api.hpp:15
static time_point now()
Definition: time.cpp:13