spinlock_std_atomic.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #ifndef BOOST_SMART_PTR_DETAIL_SPINLOCK_STD_ATOMIC_HPP_INCLUDED
  2. #define BOOST_SMART_PTR_DETAIL_SPINLOCK_STD_ATOMIC_HPP_INCLUDED
  3. // MS compatible compilers support #pragma once
  4. #if defined(_MSC_VER) && (_MSC_VER >= 1020)
  5. # pragma once
  6. #endif
  7. //
  8. // Copyright (c) 2014 Peter Dimov
  9. //
  10. // Distributed under the Boost Software License, Version 1.0.
  11. // See accompanying file LICENSE_1_0.txt or copy at
  12. // http://www.boost.org/LICENSE_1_0.txt)
  13. //
  14. #include <boost/smart_ptr/detail/yield_k.hpp>
  15. #include <boost/config.hpp>
  16. #include <atomic>
  17. #if defined(BOOST_SP_REPORT_IMPLEMENTATION)
  18. #include <boost/config/pragma_message.hpp>
  19. BOOST_PRAGMA_MESSAGE("Using std::atomic spinlock")
  20. #endif
  21. namespace boost
  22. {
  23. namespace detail
  24. {
  25. class spinlock
  26. {
  27. public:
  28. std::atomic_flag v_;
  29. public:
  30. bool try_lock() BOOST_NOEXCEPT
  31. {
  32. return !v_.test_and_set( std::memory_order_acquire );
  33. }
  34. void lock() BOOST_NOEXCEPT
  35. {
  36. for( unsigned k = 0; !try_lock(); ++k )
  37. {
  38. boost::detail::yield( k );
  39. }
  40. }
  41. void unlock() BOOST_NOEXCEPT
  42. {
  43. v_ .clear( std::memory_order_release );
  44. }
  45. public:
  46. class scoped_lock
  47. {
  48. private:
  49. spinlock & sp_;
  50. scoped_lock( scoped_lock const & );
  51. scoped_lock & operator=( scoped_lock const & );
  52. public:
  53. explicit scoped_lock( spinlock & sp ) BOOST_NOEXCEPT: sp_( sp )
  54. {
  55. sp.lock();
  56. }
  57. ~scoped_lock() /*BOOST_NOEXCEPT*/
  58. {
  59. sp_.unlock();
  60. }
  61. };
  62. };
  63. } // namespace detail
  64. } // namespace boost
  65. #define BOOST_DETAIL_SPINLOCK_INIT { ATOMIC_FLAG_INIT }
  66. #endif // #ifndef BOOST_SMART_PTR_DETAIL_SPINLOCK_STD_ATOMIC_HPP_INCLUDED