atomic_count_pthreads.hpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #ifndef DAHUA_DETAIL_ATOMIC_COUNT_PTHREADS_HPP_INCLUDED
  2. #define DAHUA_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 <pthread.h>
  13. //
  14. // The generic pthread_mutex-based implementation sometimes leads to
  15. // inefficiencies. Example: a class with two atomic_count members
  16. // can get away with a single mutex.
  17. //
  18. // Users can detect this situation by checking BOOST_AC_USE_PTHREADS.
  19. //
  20. namespace Dahua {
  21. namespace Infra {
  22. namespace Detail {
  23. class atomic_count
  24. {
  25. private:
  26. class scoped_lock
  27. {
  28. public:
  29. scoped_lock(pthread_mutex_t & m): m_(m)
  30. {
  31. pthread_mutex_lock(&m_);
  32. }
  33. ~scoped_lock()
  34. {
  35. pthread_mutex_unlock(&m_);
  36. }
  37. private:
  38. pthread_mutex_t & m_;
  39. };
  40. public:
  41. explicit atomic_count(long v): value_(v)
  42. {
  43. pthread_mutex_init(&mutex_, 0);
  44. }
  45. ~atomic_count()
  46. {
  47. pthread_mutex_destroy(&mutex_);
  48. }
  49. long operator++()
  50. {
  51. scoped_lock lock(mutex_);
  52. return ++value_;
  53. }
  54. long operator--()
  55. {
  56. scoped_lock lock(mutex_);
  57. return --value_;
  58. }
  59. operator long() const
  60. {
  61. scoped_lock lock(mutex_);
  62. return value_;
  63. }
  64. long get() const
  65. {
  66. scoped_lock lock(mutex_);
  67. return value_;
  68. }
  69. void set(long v)
  70. {
  71. scoped_lock lock(mutex_);
  72. value_ = v;
  73. return;
  74. }
  75. private:
  76. atomic_count(atomic_count const &);
  77. atomic_count & operator=(atomic_count const &);
  78. mutable pthread_mutex_t mutex_;
  79. long value_;
  80. };
  81. } // namespace Detail
  82. } // namespace Infra
  83. } // namespace Dahua
  84. #endif // #ifndef DAHUA_DETAIL_ATOMIC_COUNT_PTHREADS_HPP_INCLUDED