lean cpp library
A lean C++ library providing efficient utility classes for high-performance C++ applications.
spin_lock.h
00001 /*****************************************************/
00002 /* lean Concurrent              (c) Tobias Zirr 2011 */
00003 /*****************************************************/
00004 
00005 #ifndef LEAN_CONCURRENT_SPINLOCK
00006 #define LEAN_CONCURRENT_SPINLOCK
00007 
00008 #include "../lean.h"
00009 #include "../tags/noncopyable.h"
00010 #include "atomic.h"
00011 
00012 // Include automatically to encourage use of scoped_lock
00013 #include "../smart/scoped_lock.h"
00014 
00015 namespace lean
00016 {
00017 namespace concurrent
00018 {
00019 
00021 template <class Counter = long>
00022 class spin_lock : public noncopyable
00023 {
00024 private:
00025     Counter m_counter;
00026 
00027 public:
00029     spin_lock()
00030         : m_counter(0) {  }
00031 
00033     LEAN_INLINE bool try_lock()
00034     {
00035         return atomic_test_and_set(m_counter, static_cast<Counter>(0), static_cast<Counter>(1));
00036     }
00037 
00039     LEAN_INLINE void lock()
00040     {
00041         while (!try_lock());
00042     }
00043 
00045     LEAN_INLINE void unlock()
00046     {
00047         atomic_test_and_set(m_counter, static_cast<Counter>(1), static_cast<Counter>(0));
00048     }
00049 };
00050 
00052 typedef smart::scoped_lock< spin_lock<> > scoped_sl_lock;
00053 
00054 } // namespace
00055 
00056 using concurrent::spin_lock;
00057 
00058 using concurrent::scoped_sl_lock;
00059 
00060 } // namespace
00061 
00062 #endif