alpaka
Abstraction Library for Parallel Kernel Acceleration
Loading...
Searching...
No Matches
ManagedDealloc.hpp
Go to the documentation of this file.
1/* Copyright 2025 René Widera
2 * SPDX-License-Identifier: MPL-2.0
3 */
4
5#pragma once
6
7#include <functional>
8#include <memory>
9
11{
12 /** Manage the deallocation of memory
13 *
14 * This class is used to manage the deallocation of memory in a shared_ptr.
15 * It takes a function that will be called when the shared_ptr is destroyed.
16 * This is useful for managing memory that needs to be deallocated
17 * when the shared_ptr goes out of scope.
18 */
19 struct ManagedDealloc : std::enable_shared_from_this<ManagedDealloc>
20 {
21 /**
22 * Constructor
23 * @param freeOp Function to be called when the shared_ptr is destroyed after all actions are executed.
24 * All dependencies required to deallocate the memory must be holed by freeOp.
25 */
26 ManagedDealloc(std::function<void()> freeOp) : freeOp{std::move(freeOp)}
27 {
28 }
29
31 {
32 // Execute all actions before freeing the memory
33 for(auto& action : actions)
34 {
35 action();
36 }
37 freeOp();
38 }
39
40 /** Add an action to be executed when the shared_ptr is destroyed.
41 *
42 * @param action Callable to execute on destruction.
43 */
44 void addAction(std::function<void()> action)
45 {
46 std::lock_guard<std::mutex> lock{actionGuard};
47 actions.emplace_back(std::move(action));
48 }
49
50 std::shared_ptr<ManagedDealloc> getSharedPtr()
51 {
52 return this->shared_from_this();
53 }
54
55 private:
56 std::function<void()> freeOp;
57 std::mutex actionGuard;
58 std::vector<std::function<void()>> actions;
59 };
60} // namespace alpaka::onHost::internal
STL namespace.
std::vector< std::function< void()> > actions
std::shared_ptr< ManagedDealloc > getSharedPtr()
ManagedDealloc(std::function< void()> freeOp)
Constructor.
void addAction(std::function< void()> action)
Add an action to be executed when the shared_ptr is destroyed.