Bond
 
Loading...
Searching...
No Matches
multi_threaded_counter.h
1// Copyright (c) Microsoft. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4#pragma once
5
6#include <bond/core/config.h>
7
8#include "capped_allocator_fwd.h"
9#include "detail/counter_base.h"
10
11#include <boost/assert.hpp>
12
13#include <atomic>
14
15
16namespace bond { namespace ext
17{
21 template <typename T>
23 {
24 public:
25 using is_thread_safe = std::true_type;
26
27 using detail::counter_base<T>::counter_base;
28
29 bool try_add(T n) BOND_NOEXCEPT
30 {
31 if (n <= this->max_value())
32 {
33 const auto max_val = this->max_value() - n;
34
35 for (auto val = _value.load(std::memory_order::memory_order_acquire); val <= max_val; )
36 {
37 if (_value.compare_exchange_weak(
38 val,
39 val + n,
40 std::memory_order::memory_order_release,
41 std::memory_order::memory_order_acquire))
42 {
43 return true;
44 }
45 }
46 }
47
48 return false;
49 }
50
51 void subtract(T n) BOND_NOEXCEPT
52 {
53 BOOST_ASSERT(value() >= n);
54 _value.fetch_sub(n, std::memory_order::memory_order_relaxed);
55 }
56
58 T value() const BOND_NOEXCEPT
59 {
60 return _value.load(std::memory_order::memory_order_relaxed);
61 }
62
63 private:
64 std::atomic<T> _value{};
65 };
66
67} } // namespace bond::ext
Helper base class for counters.
Definition: counter_base.h:17
Multi-threaded counter to be used with capped_allocator.
Definition: multi_threaded_counter.h:23
T value() const BOND_NOEXCEPT
Definition: multi_threaded_counter.h:58
namespace bond
Definition: apply.h:17