thread_safe.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 Hans Dembinski
  2. //
  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)
  6. #ifndef BOOST_HISTOGRAM_ACCUMULATORS_THREAD_SAFE_HPP
  7. #define BOOST_HISTOGRAM_ACCUMULATORS_THREAD_SAFE_HPP
  8. #include <atomic>
  9. #include <boost/core/nvp.hpp>
  10. #include <boost/mp11/utility.hpp>
  11. #include <type_traits>
  12. namespace boost {
  13. namespace histogram {
  14. namespace accumulators {
  15. /** Thread-safe adaptor for builtin integral and floating point numbers.
  16. This adaptor uses std::atomic to make concurrent increments and additions safe for the
  17. stored value.
  18. On common computing platforms, the adapted integer has the same size and
  19. alignment as underlying type. The atomicity is implemented with a special CPU
  20. instruction. On exotic platforms the size of the adapted number may be larger and/or the
  21. type may have different alignment, which means it cannot be tightly packed into arrays.
  22. @tparam T type to adapt, must be supported by std::atomic.
  23. */
  24. template <class T>
  25. class thread_safe : public std::atomic<T> {
  26. public:
  27. using value_type = T;
  28. using super_t = std::atomic<T>;
  29. thread_safe() noexcept : super_t(static_cast<T>(0)) {}
  30. // non-atomic copy and assign is allowed, because storage is locked in this case
  31. thread_safe(const thread_safe& o) noexcept : super_t(o.load()) {}
  32. thread_safe& operator=(const thread_safe& o) noexcept {
  33. super_t::store(o.load());
  34. return *this;
  35. }
  36. thread_safe(value_type arg) : super_t(arg) {}
  37. thread_safe& operator=(value_type arg) {
  38. super_t::store(arg);
  39. return *this;
  40. }
  41. thread_safe& operator+=(const thread_safe& arg) {
  42. operator+=(arg.load());
  43. return *this;
  44. }
  45. thread_safe& operator+=(value_type arg) {
  46. super_t::fetch_add(arg, std::memory_order_relaxed);
  47. return *this;
  48. }
  49. thread_safe& operator++() {
  50. operator+=(static_cast<value_type>(1));
  51. return *this;
  52. }
  53. template <class Archive>
  54. void serialize(Archive& ar, unsigned /* version */) {
  55. auto value = super_t::load();
  56. ar& make_nvp("value", value);
  57. super_t::store(value);
  58. }
  59. };
  60. } // namespace accumulators
  61. } // namespace histogram
  62. } // namespace boost
  63. #endif