1 // Copyright 2019 Hans Dembinski
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt
5 // or copy at http://www.boost.org/LICENSE_1_0.txt)
7 #ifndef BOOST_HISTOGRAM_ACCUMULATORS_THREAD_SAFE_HPP
8 #define BOOST_HISTOGRAM_ACCUMULATORS_THREAD_SAFE_HPP
11 #include <boost/core/nvp.hpp>
12 #include <boost/histogram/fwd.hpp>
13 #include <type_traits>
17 namespace accumulators {
19 // cannot use new mechanism with accumulators::thread_safe
21 struct is_thread_safe<thread_safe<T>> : std::true_type {};
23 /** Thread-safe adaptor for builtin integral numbers.
25 This adaptor uses atomic operations to make concurrent increments and additions safe for
28 On common computing platforms, the adapted integer has the same size and
29 alignment as underlying type. The atomicity is implemented with a special CPU
30 instruction. On exotic platforms the size of the adapted number may be larger and/or the
31 type may have different alignment, which means it cannot be tightly packed into arrays.
33 @tparam T type to adapt, must be an integral type.
36 class [[deprecated("use count<T, true> instead; "
37 "thread_safe<T> will be removed in boost-1.79")]] thread_safe
38 : public std::atomic<T> {
41 using super_t = std::atomic<T>;
43 thread_safe() noexcept : super_t(static_cast<T>(0)) {}
44 // non-atomic copy and assign is allowed, because storage is locked in this case
45 thread_safe(const thread_safe& o) noexcept : super_t(o.load()) {}
46 thread_safe& operator=(const thread_safe& o) noexcept {
47 super_t::store(o.load());
51 thread_safe(value_type arg) : super_t(arg) {}
52 thread_safe& operator=(value_type arg) {
57 thread_safe& operator+=(const thread_safe& arg) {
58 operator+=(arg.load());
61 thread_safe& operator+=(value_type arg) {
62 super_t::fetch_add(arg, std::memory_order_relaxed);
65 thread_safe& operator++() {
66 operator+=(static_cast<value_type>(1));
70 template <class Archive>
71 void serialize(Archive & ar, unsigned /* version */) {
72 auto value = super_t::load();
73 ar& make_nvp("value", value);
74 super_t::store(value);
78 } // namespace accumulators
79 } // namespace histogram