Skip to content

Commit

Permalink
added preliminary rwlock for #18
Browse files Browse the repository at this point in the history
  • Loading branch information
lethalbit committed Apr 20, 2023
1 parent ef4019e commit 6724b3b
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions substrate/rwlock
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: BSD-3-Clause
#ifndef SUBSTRATE_RWLOCK
#define SUBSTRATE_RWLOCK

#if __cplusplus < 201703L
#error "rwlock is on available on C++17 and above"
#endif

#include <substrate/internal/defs>

#include <utility>
#include <mutex>
#include <shared_mutex>

namespace substrate
{
template<typename T>
struct rwlock final {
private:
template<typename U, template<typename> typename lock_t>
struct lock_result final {
private:
lock_t<std::shared_mutex> _lock;
U& _obj;
public:
constexpr lock_result(std::shared_mutex& mut, U& obj) noexcept :
_lock{mut}, _obj{obj} { }

SUBSTRATE_NO_DISCARD(U* operator->() noexcept { return &_obj; })
SUBSTRATE_NO_DISCARD(U& operator*() noexcept { return _obj; })
};
std::shared_mutex _mutex{};
T _obj;
public:
template<typename ...args_t>
constexpr rwlock(args_t&&... args) noexcept :
_obj{std::forward<args_t>(args)...} { }

SUBSTRATE_NO_DISCARD(lock_result<const T, std::shared_lock> read() noexcept {
return {_mutex, _obj};
})
SUBSTRATE_NO_DISCARD(lock_result<T, std::unique_lock> write() noexcept {
return {_mutex, _obj};
})
};
}

#endif /* SUBSTRATE_RWLOCK */
/* vim: set ft=cpp ts=4 sw=4 noexpandtab: */

0 comments on commit 6724b3b

Please sign in to comment.