spinlock_sync.hpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #ifndef BOOST_SMART_PTR_DETAIL_SPINLOCK_SYNC_HPP_INCLUDED
  2. #define BOOST_SMART_PTR_DETAIL_SPINLOCK_SYNC_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) 2008 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. #if defined( __ia64__ ) && defined( __INTEL_COMPILER )
  16. # include <ia64intrin.h>
  17. #endif
  18. namespace boost
  19. {
  20. namespace detail
  21. {
  22. class spinlock
  23. {
  24. public:
  25. int v_;
  26. public:
  27. bool try_lock()
  28. {
  29. int r = __sync_lock_test_and_set( &v_, 1 );
  30. return r == 0;
  31. }
  32. void lock()
  33. {
  34. for( unsigned k = 0; !try_lock(); ++k )
  35. {
  36. boost::detail::yield( k );
  37. }
  38. }
  39. void unlock()
  40. {
  41. __sync_lock_release( &v_ );
  42. }
  43. public:
  44. class scoped_lock
  45. {
  46. private:
  47. spinlock & sp_;
  48. scoped_lock( scoped_lock const & );
  49. scoped_lock & operator=( scoped_lock const & );
  50. public:
  51. explicit scoped_lock( spinlock & sp ): sp_( sp )
  52. {
  53. sp.lock();
  54. }
  55. ~scoped_lock()
  56. {
  57. sp_.unlock();
  58. }
  59. };
  60. };
  61. } // namespace detail
  62. } // namespace boost
  63. #define BOOST_DETAIL_SPINLOCK_INIT {0}
  64. #endif // #ifndef BOOST_SMART_PTR_DETAIL_SPINLOCK_SYNC_HPP_INCLUDED