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