19 #ifndef ASYLO_PLATFORM_CORE_SHARED_RESOURCE_MANAGER_H_ 20 #define ASYLO_PLATFORM_CORE_SHARED_RESOURCE_MANAGER_H_ 24 #include "absl/container/flat_hash_map.h" 25 #include "absl/synchronization/mutex.h" 26 #include "asylo/platform/core/shared_name.h" 27 #include "asylo/util/status.h" 35 class SharedResourceManager {
54 template <
typename T,
typename Deleter = std::default_delete<T>>
56 absl::MutexLock lock(&mu_);
57 auto *resource =
new ManagedResource<T, Deleter>(name, pointer);
58 return InstallResource(resource);
72 absl::MutexLock lock(&mu_);
73 auto *resource =
new UnmanagedResource<T>(name, pointer);
74 return InstallResource(resource);
84 absl::MutexLock lock(&mu_);
85 auto it = shared_resources_.find(name);
86 if (it == shared_resources_.end()) {
89 it->second->reference_count++;
90 return static_cast<T *>(it->second->get());
105 struct ResourceHandle {
106 ResourceHandle(
const SharedName &name)
107 : resource_name(name), reference_count(1) {}
108 virtual ~ResourceHandle() =
default;
111 virtual void *get() = 0;
115 virtual void release() = 0;
117 SharedName resource_name;
122 template <
typename T,
typename Deleter>
123 struct ManagedResource :
public ResourceHandle {
124 ManagedResource(
const SharedName &name, T *pointer)
125 : ResourceHandle(name), resource(pointer) {}
126 void *get()
override {
return static_cast<
void *>(resource.get()); }
127 void release()
override { resource.release(); }
128 std::unique_ptr<T, Deleter> resource;
132 template <
typename T>
133 struct UnmanagedResource :
public ResourceHandle {
134 UnmanagedResource(
const SharedName &name, T *pointer)
135 : ResourceHandle(name), resource(pointer) {}
136 void *get()
override {
return static_cast<
void *>(resource); }
137 void release()
override {}
143 Status InstallResource(ResourceHandle *handle)
144 ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
147 absl::flat_hash_map<SharedName, std::unique_ptr<ResourceHandle>,
148 SharedName::Hash, SharedName::Eq>
T * AcquireResource(const SharedName &name)
Acquires a named resource.
Definition: shared_resource_manager.h:83
Status RegisterUnmanagedResource(const SharedName &name, T *pointer)
Registers a shared resource owned by that remains owned by the caller.
Definition: shared_resource_manager.h:71
ABSL_CONST_INIT const char kStatusMoveAssignmentMsg[]
bool ReleaseResource(const SharedName &name)
Releases a named resource.
Status RegisterManagedResource(const SharedName &name, T *pointer)
Registers a shared resource and passes ownership to the SharedResourceManager.
Definition: shared_resource_manager.h:55