37#include <unordered_map>
42template<
typename resource_t,
typename mtx_t>
52template<
typename resource_t,
typename mutex_t,
typename key_t,
53 typename lock_t = std::unique_lock<mutex_t>>
69 auto&
resource() {
return lockable_m.resource; }
71 auto&
guard() {
return guard_m; }
73 auto&
key() {
return key_m; }
81template<
typename key_t,
typename resource_t,
typename mutex_t = std::mutex>
93 auto guard = std::lock_guard{mtx_m};
95 return resources_m.size();
100 auto guard = std::lock_guard{mtx_m};
102 return resources_m.contains(key);
105 template<
class... args_t>
108 if (resources_m.contains(key))
109 return find_locked(key, resources_m);
110 return emplace(key, std::forward<args>(args)...);
113 template<
class... args_t>
116 auto guard = std::lock_guard{mtx_m};
118 auto mtx = mtxs_m.try_emplace(key);
121 throw std::runtime_error(std::format(
122 "Unable to emplace a new Resource Mutex [key: 0x{:X}]", key));
124 auto res = resources_m.try_emplace(key, std::forward<args_t>(args)...);
128 mtxs_m.erase(mtx.first);
130 throw std::runtime_error(
131 std::format(
"Unable to emplace a new Resource [key: 0x{:X}]", key));
136 return locked{
lockable{res.first->second, mtx.first->second}, key};
142 return find_locked(k, resources_m);
147 auto guard = std::lock_guard{mtx_m};
150 auto guard = std::lock_guard{mtxs_m.at(k)};
152 resources_m.erase(k);
159 auto find_locked(
const key_type key,
160 std::unordered_map<key_type, resource_type>& xs)
163 auto guard = std::lock_guard{mtx_m};
165 if (!xs.contains(key))
166 throw std::out_of_range(
167 std::format(
"Object not found for Key 0x{:X}", key));
169 auto& x = xs.at(key);
171 return locked{lockable{x, mtxs_m.at(key)}, key};
175 std::unordered_map<key_type, mutex_type>
177 std::unordered_map<key_type, resource_type> resources_m;
bool contains(const key_type key)
auto emplace(const key_type key, args_t &&... args)
auto find_or_emplace(const key_type key, args_t &&... args)
void delete_resource(key_type k)
auto locked_resource(const key_type k) -> locked< resource_type, mutex_type, key_type >
void debug(spdlog::source_loc loc, pars::lf lf, spdlog::format_string_t< args_t... > fmt, args_t &&... args)
locked(lockable< resource_type, mutex_type > l, key_type k)