1 ////////////////////////////////////////////////////////////////////////////// 2 // 3 // (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost 4 // Software License, Version 1.0. (See accompanying file 5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6 // 7 // See http://www.boost.org/libs/interprocess for documentation. 8 // 9 ////////////////////////////////////////////////////////////////////////////// 10 11 #ifndef BOOST_INTERPROCESS_DETAIL_SPIN_SEMAPHORE_HPP 12 #define BOOST_INTERPROCESS_DETAIL_SPIN_SEMAPHORE_HPP 13 14 #ifndef BOOST_CONFIG_HPP 15 # include <boost/config.hpp> 16 #endif 17 # 18 #if defined(BOOST_HAS_PRAGMA_ONCE) 19 # pragma once 20 #endif 21 22 #include <boost/interprocess/detail/config_begin.hpp> 23 #include <boost/interprocess/detail/workaround.hpp> 24 #include <boost/interprocess/detail/atomic.hpp> 25 #include <boost/interprocess/detail/os_thread_functions.hpp> 26 #include <boost/interprocess/detail/posix_time_types_wrk.hpp> 27 #include <boost/interprocess/sync/detail/common_algorithms.hpp> 28 #include <boost/interprocess/sync/detail/locks.hpp> 29 #include <boost/cstdint.hpp> 30 31 namespace boost { 32 namespace interprocess { 33 namespace ipcdetail { 34 35 class spin_semaphore 36 { 37 spin_semaphore(const spin_semaphore &); 38 spin_semaphore &operator=(const spin_semaphore &); 39 40 public: 41 spin_semaphore(unsigned int initialCount); 42 ~spin_semaphore(); 43 44 void post(); 45 void wait(); 46 bool try_wait(); 47 bool timed_wait(const boost::posix_time::ptime &abs_time); 48 49 // int get_count() const; 50 private: 51 volatile boost::uint32_t m_count; 52 }; 53 54 ~spin_semaphore()55inline spin_semaphore::~spin_semaphore() 56 {} 57 spin_semaphore(unsigned int initialCount)58inline spin_semaphore::spin_semaphore(unsigned int initialCount) 59 { ipcdetail::atomic_write32(&this->m_count, boost::uint32_t(initialCount)); } 60 post()61inline void spin_semaphore::post() 62 { 63 ipcdetail::atomic_inc32(&m_count); 64 } 65 wait()66inline void spin_semaphore::wait() 67 { 68 ipcdetail::lock_to_wait<spin_semaphore> lw(*this); 69 return ipcdetail::try_based_lock(lw); 70 } 71 try_wait()72inline bool spin_semaphore::try_wait() 73 { 74 return ipcdetail::atomic_add_unless32(&m_count, boost::uint32_t(-1), boost::uint32_t(0)); 75 } 76 timed_wait(const boost::posix_time::ptime & abs_time)77inline bool spin_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) 78 { 79 ipcdetail::lock_to_wait<spin_semaphore> lw(*this); 80 return ipcdetail::try_based_timed_lock(lw, abs_time); 81 } 82 83 //inline int spin_semaphore::get_count() const 84 //{ 85 //return (int)ipcdetail::atomic_read32(&m_count); 86 //} 87 88 } //namespace ipcdetail { 89 } //namespace interprocess { 90 } //namespace boost { 91 92 #include <boost/interprocess/detail/config_end.hpp> 93 94 #endif //BOOST_INTERPROCESS_DETAIL_SPIN_SEMAPHORE_HPP 95