Skip to content

Commit

Permalink
Add locked_access
Browse files Browse the repository at this point in the history
  • Loading branch information
davidstone committed Dec 24, 2023
1 parent 330ebf3 commit 507ad06
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand Down
1 change: 1 addition & 0 deletions source/concurrent.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@

export module concurrent;

export import concurrent.locked_access;
export import concurrent.queue;
48 changes: 48 additions & 0 deletions source/locked_access.cpp
Original file line number Diff line number Diff line change
@@ -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<typename T, typename Mutex>
struct locked_t {
static_assert(std::is_reference_v<T>);
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<Mutex> m_lock;
};
template<typename T, typename Mutex>
locked_t(T &, Mutex &) -> locked_t<T &, Mutex>;

export template<typename T, typename Mutex = std::mutex>
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

0 comments on commit 507ad06

Please sign in to comment.