Skip to content

Commit bfe960d

Browse files
committed
Specify memory ordering when reference counting with standard atomics.
1 parent 9d2c453 commit bfe960d

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

include/boost/asio/detail/atomic_count.hpp

+19
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,31 @@ namespace detail {
3232
#if !defined(BOOST_ASIO_HAS_THREADS)
3333
typedef long atomic_count;
3434
inline void increment(atomic_count& a, long b) { a += b; }
35+
inline void ref_count_up(atomic_count& a) { ++a; }
36+
inline bool ref_count_down(atomic_count& a) { return --a == 0; }
3537
#elif defined(BOOST_ASIO_HAS_STD_ATOMIC)
3638
typedef std::atomic<long> atomic_count;
3739
inline void increment(atomic_count& a, long b) { a += b; }
40+
41+
inline void ref_count_up(atomic_count& a)
42+
{
43+
a.fetch_add(1, std::memory_order_relaxed);
44+
}
45+
46+
inline bool ref_count_down(atomic_count& a)
47+
{
48+
if (a.fetch_sub(1, std::memory_order_release) == 1)
49+
{
50+
std::atomic_thread_fence(std::memory_order_acquire);
51+
return true;
52+
}
53+
return false;
54+
}
3855
#else // defined(BOOST_ASIO_HAS_STD_ATOMIC)
3956
typedef boost::detail::atomic_count atomic_count;
4057
inline void increment(atomic_count& a, long b) { while (b > 0) ++a, --b; }
58+
inline void ref_count_up(atomic_count& a) { ++a; }
59+
inline bool ref_count_down(atomic_count& a) { return --a == 0; }
4160
#endif // defined(BOOST_ASIO_HAS_STD_ATOMIC)
4261

4362
} // namespace detail

include/boost/asio/impl/executor.hpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,13 @@ class executor::impl
149149

150150
impl_base* clone() const BOOST_ASIO_NOEXCEPT
151151
{
152-
++ref_count_;
152+
detail::ref_count_up(ref_count_);
153153
return const_cast<impl_base*>(static_cast<const impl_base*>(this));
154154
}
155155

156156
void destroy() BOOST_ASIO_NOEXCEPT
157157
{
158-
if (--ref_count_ == 0)
158+
if (detail::ref_count_down(ref_count_))
159159
{
160160
allocator_type alloc(allocator_);
161161
impl* p = this;

0 commit comments

Comments
 (0)