atomic_count_pt.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. #if defined(BOOST_SP_REPORT_IMPLEMENTATION)
  15. #include <boost/config/pragma_message.hpp>
  16. BOOST_PRAGMA_MESSAGE("Using pthread_mutex atomic_count")
  17. #endif
  18. //
  19. // The generic pthread_mutex-based implementation sometimes leads to
  20. // inefficiencies. Example: a class with two atomic_count members
  21. // can get away with a single mutex.
  22. //
  23. // Users can detect this situation by checking BOOST_AC_USE_PTHREADS.
  24. //
  25. namespace boost
  26. {
  27. namespace detail
  28. {
  29. class atomic_count
  30. {
  31. private:
  32. class scoped_lock
  33. {
  34. public:
  35. scoped_lock(pthread_mutex_t & m): m_(m)
  36. {
  37. BOOST_VERIFY( pthread_mutex_lock( &m_ ) == 0 );
  38. }
  39. ~scoped_lock()
  40. {
  41. BOOST_VERIFY( pthread_mutex_unlock( &m_ ) == 0 );
  42. }
  43. private:
  44. pthread_mutex_t & m_;
  45. };
  46. public:
  47. explicit atomic_count(long v): value_(v)
  48. {
  49. BOOST_VERIFY( pthread_mutex_init( &mutex_, 0 ) == 0 );
  50. }
  51. ~atomic_count()
  52. {
  53. BOOST_VERIFY( pthread_mutex_destroy( &mutex_ ) == 0 );
  54. }
  55. long operator++()
  56. {
  57. scoped_lock lock(mutex_);
  58. return ++value_;
  59. }
  60. long operator--()
  61. {
  62. scoped_lock lock(mutex_);
  63. return --value_;
  64. }
  65. operator long() const
  66. {
  67. scoped_lock lock(mutex_);
  68. return value_;
  69. }
  70. private:
  71. atomic_count(atomic_count const &);
  72. atomic_count & operator=(atomic_count const &);
  73. mutable pthread_mutex_t mutex_;
  74. long value_;
  75. };
  76. } // namespace detail
  77. } // namespace boost
  78. #endif // #ifndef BOOST_SMART_PTR_DETAIL_ATOMIC_COUNT_PTHREADS_HPP_INCLUDED