From 507ad06302c2345bed8f57e0ddf6092c6cf5cbbf Mon Sep 17 00:00:00 2001 From: David Stone Date: Sun, 24 Dec 2023 14:01:05 -0700 Subject: [PATCH] Add `locked_access` --- CMakeLists.txt | 1 + source/concurrent.cpp | 1 + source/locked_access.cpp | 48 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 source/locked_access.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4d7514d..0b37308 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,6 +54,7 @@ target_sources(concurrent PUBLIC BASE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}" FILES source/concurrent.cpp + source/locked_access.cpp source/queue.cpp ) diff --git a/source/concurrent.cpp b/source/concurrent.cpp index 3a990b6..201ab7d 100644 --- a/source/concurrent.cpp +++ b/source/concurrent.cpp @@ -5,4 +5,5 @@ export module concurrent; +export import concurrent.locked_access; export import concurrent.queue; \ No newline at end of file diff --git a/source/locked_access.cpp b/source/locked_access.cpp new file mode 100644 index 0000000..c3d9939 --- /dev/null +++ b/source/locked_access.cpp @@ -0,0 +1,48 @@ +// Copyright David Stone 2023. +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +export module concurrent.locked_access; + +import std_module; + +namespace concurrent { + +template +struct locked_t { + static_assert(std::is_reference_v); + constexpr locked_t(T value_, Mutex & mutex): + m_value(value_), + m_lock(mutex) + { + } + constexpr auto value() const & -> T { + return m_value; + } + auto value() && = delete; +private: + T m_value; + std::unique_lock m_lock; +}; +template +locked_t(T &, Mutex &) -> locked_t; + +export template +struct locked_access { + constexpr auto locked() & { + return locked_t(m_value, m_mutex); + } + constexpr auto locked() const & { + return locked_t(m_value, m_mutex); + } + constexpr auto unlocked() const -> T const & { + return m_value; + } + +private: + mutable Mutex m_mutex; + [[no_unique_address]] T m_value; +}; + +} // namespace concurrent \ No newline at end of file