1 //////////////////////////////////////////////////////////////////////////////
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)
7 // See http://www.boost.org/libs/interprocess for documentation.
9 //////////////////////////////////////////////////////////////////////////////
11 #ifndef BOOST_INTERPROCESS_DETAIL_SPIN_MUTEX_HPP
12 #define BOOST_INTERPROCESS_DETAIL_SPIN_MUTEX_HPP
14 #ifndef BOOST_CONFIG_HPP
15 # include <boost/config.hpp>
18 #if defined(BOOST_HAS_PRAGMA_ONCE)
22 #include <boost/interprocess/detail/config_begin.hpp>
23 #include <boost/interprocess/detail/workaround.hpp>
24 #include <boost/interprocess/detail/posix_time_types_wrk.hpp>
25 #include <boost/assert.hpp>
26 #include <boost/interprocess/detail/atomic.hpp>
27 #include <boost/cstdint.hpp>
28 #include <boost/interprocess/detail/os_thread_functions.hpp>
29 #include <boost/interprocess/sync/detail/common_algorithms.hpp>
32 namespace interprocess {
37 spin_mutex(const spin_mutex &);
38 spin_mutex &operator=(const spin_mutex &);
46 bool timed_lock(const boost::posix_time::ptime &abs_time);
48 void take_ownership(){}
50 volatile boost::uint32_t m_s;
53 inline spin_mutex::spin_mutex()
56 //Note that this class is initialized to zero.
57 //So zeroed memory can be interpreted as an
61 inline spin_mutex::~spin_mutex()
66 inline void spin_mutex::lock(void)
68 #ifdef BOOST_INTERPROCESS_ENABLE_TIMEOUT_WHEN_LOCKING
69 boost::posix_time::ptime wait_time
70 = microsec_clock::universal_time()
71 + boost::posix_time::milliseconds(BOOST_INTERPROCESS_TIMEOUT_WHEN_LOCKING_DURATION_MS);
72 if (!timed_lock(wait_time))
74 throw interprocess_exception(timeout_when_locking_error
75 , "Interprocess mutex timeout when locking. Possible deadlock: "
76 "owner died without unlocking?");
79 return ipcdetail::try_based_lock(*this);
83 inline bool spin_mutex::try_lock(void)
85 boost::uint32_t prev_s = ipcdetail::atomic_cas32(const_cast<boost::uint32_t*>(&m_s), 1, 0);
86 return m_s == 1 && prev_s == 0;
89 inline bool spin_mutex::timed_lock(const boost::posix_time::ptime &abs_time)
90 { return ipcdetail::try_based_timed_lock(*this, abs_time); }
92 inline void spin_mutex::unlock(void)
93 { ipcdetail::atomic_cas32(const_cast<boost::uint32_t*>(&m_s), 0, 1); }
95 } //namespace ipcdetail {
96 } //namespace interprocess {
99 #include <boost/interprocess/detail/config_end.hpp>
101 #endif //BOOST_INTERPROCESS_DETAIL_SPIN_MUTEX_HPP