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#include <mutex>
10#include <vector>
11
12namespace alpaka::onHost::internal
13{
14 /** Manage the deallocation of memory
15 *
16 * This class is used to manage the deallocation of memory in a shared_ptr.
17 * It takes a function that will be called when the shared_ptr is destroyed.
18 * This is useful for managing memory that needs to be deallocated
19 * when the shared_ptr goes out of scope.
20 */
21 struct ManagedDealloc : std::enable_shared_from_this<ManagedDealloc>
22 {
23 /**
24 * Constructor
25 * @param freeOp Function to be called when the shared_ptr is destroyed after all actions are executed.
26 * All dependencies required to deallocate the memory must be holed by freeOp.
27 */
28 ManagedDealloc(std::function<void()> freeOp) : freeOp{std::move(freeOp)}
29 {
30 }
31
32 ~ManagedDealloc()
33 {
34 // Execute all actions before freeing the memory
35 for(auto& action : actions)
36 {
37 action();
38 }
39 freeOp();
40 }
41
42 /** Add an action to be executed when the shared_ptr is destroyed.
43 *
44 * @param action Callable to execute on destruction.
45 */
46 void addAction(std::function<void()> action)
47 {
48 std::lock_guard<std::mutex> lock{actionGuard};
49 actions.emplace_back(std::move(action));
50 }
51
52 std::shared_ptr<ManagedDealloc> getSharedPtr()
53 {
54 return this->shared_from_this();
55 }
56
57 private:
58 std::function<void()> freeOp;
59 std::mutex actionGuard;
60 std::vector<std::function<void()>> actions;
61 };
62} // namespace alpaka::onHost::internal