Bytemaster's Boost Libraries
/Users/dlarimer/dev/libs/cmt/include/boost/cmt/mutex.hpp
00001 #ifndef _BOOST_CMT_MUTEX_HPP_
00002 #define _BOOST_CMT_MUTEX_HPP_
00003 #include <boost/atomic.hpp>
00004 #include <boost/memory_order.hpp>
00005 
00006 namespace boost{ namespace cmt {
00008     void yield();
00009 
00019     class mutex {
00020         public:
00021             mutex():m_state(unlocked){}
00022 
00023             inline bool try_lock() {
00024                 return m_state.exchange(locked, boost::memory_order_acquire)!=locked;
00025             }
00026 
00027             template<typename DurationType>
00028             bool timed_lock( const DurationType& rel_time ) {
00029                 return timed_lock( boost::get_system_time() + rel_time );
00030             }
00031 
00032             bool timed_lock( const boost::system_time& abs_time) {
00033                 while( abs_time > boost::get_system_time() ) {
00034                    if( try_lock() )
00035                      return true;
00036                    yield(); 
00037                 }
00038                 return false;
00039             }
00040             void lock() {
00041                 while( m_state.exchange(locked, boost::memory_order_acquire)==locked) {
00042                    yield(); 
00043                 }
00044             }
00045             void unlock() {
00046                 m_state.store(unlocked, boost::memory_order_release);
00047             }
00048             
00049         private:
00050             enum lock_state {locked,unlocked};
00051             boost::atomic<lock_state> m_state;
00052     };
00053 
00054 } } // namespace boost::cmt
00055 
00056 #endif // _BOOST_CMT_MUTEX_HPP_
 All Classes Namespaces Files Functions Variables Typedefs Defines