NUMA++ 0.12.0
Loading...
Searching...
No Matches
allocHugeExample.cpp
Go to the documentation of this file.
1/**
2 * @file
3 * @copyright
4 * SPDX-FileCopyrightText: 2025-2025 European Southern Observatory (ESO)
5 *
6 * SPDX-License-Identifier: LGPL-3.0-only
7 */
8#include <numapp/memory.hpp>
9
10void Example() {
11 // Allocate 16MiB from NUMA node 1 in 2MiB pages.
12 auto const size = 16 * 1024 * 1024;
13 auto const page_size = numapp::HugePagePreset::Huge2M;
14
15 // 1) AllocateHuge will allocate size, rounding up to nearest page_size
16 // multiple
17 void* ptr = numapp::AllocateHuge(size,
18 page_size,
20 numapp::MemPolicyFlag::Strict);
21
22 // 2) It is particularly important to pre-fault huge-pages as the likelihood
23 // for failure is higher. If page-fault would fail when memory is accessed
24 // the result is a segmentation fault.
25 if (auto ec = numapp::MemLock(ptr, size, numapp::LockFlag::PreFault); ec) {
26 // Page-fault failed; this would have caused a segmentation fault if not
27 // for `numapp::MemLock()`.
28 throw std::system_error(ec, "Page fault failed");
29 }
30
31 // 3) FreeHuge will free memory, rounding up to nearest page_size multiple
32 // as required by mmap.
33 numapp::FreeHuge(ptr, size, page_size);
34}
static MemPolicy MakeBindNode(int node)
Creates a strict policy (using MPOL_BIND) to allocate all memory to the specified node.
void FreeHuge(void *ptr, std::size_t size, HugePageSize page_size, std::error_code &ec) noexcept
Free huge pages previously allocated with AllocateHuge.
Definition memory.cpp:207
void * AllocateHuge(std::size_t size, HugePageSize page_size, MemPolicy const &policy, MemPolicyFlag flags, std::error_code &ec) noexcept
Non-throwing version of AllocateHuge()
Definition memory.cpp:167
@ Huge2M
2 MiB page size.
Definition memory.hpp:507
std::error_code MemLock(void const *addr, std::size_t len, LockFlag flag) noexcept
Lock memory pages in the specified address range.
Definition memory.cpp:60
@ PreFault
Locks pages whether they are resident or not.
Definition memory.hpp:128
Contains memory function declarations.