atomic_count_pt.hpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #ifndef BOOST_SMART_PTR_DETAIL_ATOMIC_COUNT_PTHREADS_HPP_INCLUDED
  2. #define BOOST_SMART_PTR_DETAIL_ATOMIC_COUNT_PTHREADS_HPP_INCLUDED
  3. //
  4. // boost/detail/atomic_count_pthreads.hpp
  5. //
  6. // Copyright (c) 2001, 2002 Peter Dimov and Multi Media Ltd.
  7. //
  8. // Distributed under the Boost Software License, Version 1.0. (See
  9. // accompanying file LICENSE_1_0.txt or copy at
  10. // http://www.boost.org/LICENSE_1_0.txt)
  11. //
  12. #include <boost/assert.hpp>
  13. #include <pthread.h>
  14. //
  15. // The generic pthread_mutex-based implementation sometimes leads to
  16. // inefficiencies. Example: a class with two atomic_count members
  17. // can get away with a single mutex.
  18. //
  19. // Users can detect this situation by checking BOOST_AC_USE_PTHREADS.
  20. //
  21. namespace boost
  22. {
  23. namespace detail
  24. {
  25. class atomic_count
  26. {
  27. private:
  28. class scoped_lock
  29. {
  30. public:
  31. scoped_lock(pthread_mutex_t & m): m_(m)
  32. {
  33. BOOST_VERIFY( pthread_mutex_lock( &m_ ) == 0 );
  34. }
  35. ~scoped_lock()
  36. {
  37. BOOST_VERIFY( pthread_mutex_unlock( &m_ ) == 0 );
  38. }
  39. private:
  40. pthread_mutex_t & m_;
  41. };
  42. public:
  43. explicit atomic_count(long v): value_(v)
  44. {
  45. BOOST_VERIFY( pthread_mutex_init( &mutex_, 0 ) == 0 );
  46. }
  47. ~atomic_count()
  48. {
  49. BOOST_VERIFY( pthread_mutex_destroy( &mutex_ ) == 0 );
  50. }
  51. long operator++()
  52. {
  53. scoped_lock lock(mutex_);
  54. return ++value_;
  55. }
  56. long operator--()
  57. {
  58. scoped_lock lock(mutex_);
  59. return --value_;
  60. }
  61. operator long() const
  62. {
  63. scoped_lock lock(mutex_);
  64. return value_;
  65. }
  66. private:
  67. atomic_count(atomic_count const &);
  68. atomic_count & operator=(atomic_count const &);
  69. mutable pthread_mutex_t mutex_;
  70. long value_;
  71. };
  72. } // namespace detail
  73. } // namespace boost
  74. #endif // #ifndef BOOST_SMART_PTR_DETAIL_ATOMIC_COUNT_PTHREADS_HPP_INCLUDED