From cafd0b629bbcdbc454a372d643fd9b719fbb10ed Mon Sep 17 00:00:00 2001 From: Kevin Heifner Date: Fri, 5 Apr 2024 08:41:03 -0500 Subject: [PATCH] GH-2102 Add a large_atomic wrapper around mutex --- .../include/eosio/chain/thread_utils.hpp | 38 +++++++++++++++++++ plugins/net_plugin/net_plugin.cpp | 10 ----- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/libraries/chain/include/eosio/chain/thread_utils.hpp b/libraries/chain/include/eosio/chain/thread_utils.hpp index d3e9e8a261..f687096aaa 100644 --- a/libraries/chain/include/eosio/chain/thread_utils.hpp +++ b/libraries/chain/include/eosio/chain/thread_utils.hpp @@ -12,6 +12,44 @@ namespace eosio { namespace chain { + // should be defined for c++17, but clang++16 still has not implemented it +#ifdef __cpp_lib_hardware_interference_size + using std::hardware_constructive_interference_size; + using std::hardware_destructive_interference_size; +#else + // 64 bytes on x86-64 │ L1_CACHE_BYTES │ L1_CACHE_SHIFT │ __cacheline_aligned │ ... + [[maybe_unused]] constexpr std::size_t hardware_constructive_interference_size = 64; + [[maybe_unused]] constexpr std::size_t hardware_destructive_interference_size = 64; +#endif + + // Use instead of std::atomic when std::atomic does not support type + template + class large_atomic { + alignas(hardware_destructive_interference_size) + mutable std::mutex mtx; + T value{}; + public: + T load() const { + std::lock_guard g(mtx); + return value; + } + void store(const T& v) { + std::lock_guard g(mtx); + value = v; + } + + class accessor { + std::lock_guard g; + T& v; + public: + accessor(std::mutex& m, T& v) + : g(m), v(v) {} + T& value() { return v; } + }; + + auto make_accessor() { return accessor{mtx, value}; } + }; + /** * Wrapper class for thread pool of boost asio io_context run. * Also names threads so that tools like htop can see thread name. diff --git a/plugins/net_plugin/net_plugin.cpp b/plugins/net_plugin/net_plugin.cpp index 8da4b26a70..a3ab7201fe 100644 --- a/plugins/net_plugin/net_plugin.cpp +++ b/plugins/net_plugin/net_plugin.cpp @@ -33,16 +33,6 @@ #include #include -// should be defined for c++17, but clang++16 still has not implemented it -#ifdef __cpp_lib_hardware_interference_size - using std::hardware_constructive_interference_size; - using std::hardware_destructive_interference_size; -#else - // 64 bytes on x86-64 │ L1_CACHE_BYTES │ L1_CACHE_SHIFT │ __cacheline_aligned │ ... - [[maybe_unused]] constexpr std::size_t hardware_constructive_interference_size = 64; - [[maybe_unused]] constexpr std::size_t hardware_destructive_interference_size = 64; -#endif - using namespace eosio::chain::plugin_interface; using namespace std::chrono_literals;