PCB Environment 2
Loading...
Searching...
No Matches
HugePageAllocator.hpp
1#pragma once
2
3#include <cstddef>
4#include <cstdlib>
5#include <memory>
6
7#if defined(_WIN32)
8
9template<typename T> using AlignedTHPAllocator = std::allocator<T>;
10
11#else
12
13#include <cstring>
14#include <new>
15#include <stdexcept>
16#include <sys/mman.h>
17#include <unistd.h>
18#include <vector>
19
20constexpr std::size_t hugepage_size = 2 * 1024 * 1024;
21
22template<typename T> struct AlignedTHPAllocator
23{
24 using value_type = T;
25
26 AlignedTHPAllocator() = default;
27
28 template<class U> constexpr AlignedTHPAllocator(const AlignedTHPAllocator<U>&) noexcept { }
29
30 T *allocate(std::size_t n)
31 {
32 std::size_t bytes = n * sizeof(T);
33 void *ptr = nullptr;
34 int res = posix_memalign(&ptr, hugepage_size, bytes);
35 if (res != 0 || ptr == nullptr)
36 throw std::bad_alloc();
37 madvise(ptr, bytes, MADV_HUGEPAGE);
38 return static_cast<T *>(ptr);
39 }
40
41 void deallocate(T *p, std::size_t n) noexcept
42 {
43 std::free(p);
44 }
45};
46
47template<typename T, typename U> bool operator==(const AlignedTHPAllocator<T>&, const AlignedTHPAllocator<U>&) { return true; }
48template<typename T, typename U> bool operator!=(const AlignedTHPAllocator<T>&, const AlignedTHPAllocator<U>&) { return false; }
49
50#endif // _WIN32
Definition HugePageAllocator.hpp:23