sp_counted_base_solaris.hpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #ifndef BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SOLARIS_HPP_INCLUDED
  2. #define BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SOLARIS_HPP_INCLUDED
  3. //
  4. // detail/sp_counted_base_solaris.hpp
  5. // based on: detail/sp_counted_base_w32.hpp
  6. //
  7. // Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd.
  8. // Copyright 2004-2005 Peter Dimov
  9. // Copyright 2006 Michael van der Westhuizen
  10. //
  11. // Distributed under the Boost Software License, Version 1.0. (See
  12. // accompanying file LICENSE_1_0.txt or copy at
  13. // http://www.boost.org/LICENSE_1_0.txt)
  14. //
  15. //
  16. // Lock-free algorithm by Alexander Terekhov
  17. //
  18. // Thanks to Ben Hitchings for the #weak + (#shared != 0)
  19. // formulation
  20. //
  21. #include <boost/detail/sp_typeinfo.hpp>
  22. #include <atomic.h>
  23. namespace boost
  24. {
  25. namespace detail
  26. {
  27. class sp_counted_base
  28. {
  29. private:
  30. sp_counted_base( sp_counted_base const & );
  31. sp_counted_base & operator= ( sp_counted_base const & );
  32. uint32_t use_count_; // #shared
  33. uint32_t weak_count_; // #weak + (#shared != 0)
  34. public:
  35. sp_counted_base(): use_count_( 1 ), weak_count_( 1 )
  36. {
  37. }
  38. virtual ~sp_counted_base() // nothrow
  39. {
  40. }
  41. // dispose() is called when use_count_ drops to zero, to release
  42. // the resources managed by *this.
  43. virtual void dispose() = 0; // nothrow
  44. // destroy() is called when weak_count_ drops to zero.
  45. virtual void destroy() // nothrow
  46. {
  47. delete this;
  48. }
  49. virtual void * get_deleter( sp_typeinfo const & ti ) = 0;
  50. void add_ref_copy()
  51. {
  52. atomic_inc_32( &use_count_ );
  53. }
  54. bool add_ref_lock() // true on success
  55. {
  56. for( ;; )
  57. {
  58. uint32_t tmp = static_cast< uint32_t const volatile& >( use_count_ );
  59. if( tmp == 0 ) return false;
  60. if( atomic_cas_32( &use_count_, tmp, tmp + 1 ) == tmp ) return true;
  61. }
  62. }
  63. void release() // nothrow
  64. {
  65. if( atomic_dec_32_nv( &use_count_ ) == 0 )
  66. {
  67. dispose();
  68. weak_release();
  69. }
  70. }
  71. void weak_add_ref() // nothrow
  72. {
  73. atomic_inc_32( &weak_count_ );
  74. }
  75. void weak_release() // nothrow
  76. {
  77. if( atomic_dec_32_nv( &weak_count_ ) == 0 )
  78. {
  79. destroy();
  80. }
  81. }
  82. long use_count() const // nothrow
  83. {
  84. return static_cast<long const volatile &>( use_count_ );
  85. }
  86. };
  87. } // namespace detail
  88. } // namespace boost
  89. #endif // #ifndef BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SOLARIS_HPP_INCLUDED