DASH  0.3.0
GlobalAllocator.h
1 #ifndef DASH__ALLOCATOR__GLOBAL_ALLOCATOR_H__INCLUDED
2 #define DASH__ALLOCATOR__GLOBAL_ALLOCATOR_H__INCLUDED
3 
4 #include <dash/memory/MemorySpace.h>
5 #include <type_traits>
6 
7 namespace dash {
8 
9 namespace detail {
10 template <class T>
11 struct remove_cvref {
12  typedef std::remove_cv_t<std::remove_reference_t<T>> type;
13 };
14 } // namespace detail
15 
16 template <class T, class GlobMemType>
18 public:
22  template <class U>
24 
25  // value type
26  using value_type = typename detail::remove_cvref<T>::type;
27 
28  // Obtain correct pointer type for T
29  using pointer = typename std::pointer_traits<
30  typename GlobMemType::void_pointer>::template rebind<value_type>;
31 
32  using memory_resource = GlobMemType;
33 
34 public:
35  constexpr GlobalAllocator() noexcept = default;
36  constexpr explicit GlobalAllocator(
37  memory_resource* memory_resource) noexcept
38  : m_resource(memory_resource)
39  {
40  }
41 
42  template <class U>
44  : m_resource(other.resource())
45  {
46  }
47 
48  pointer allocate(std::size_t n)
49  {
50  using memory_traits = dash::memory_space_traits<GlobMemType>;
51  constexpr bool is_contiguous = std::is_same<
52  typename memory_traits::memory_space_layout_tag,
54  pointer p = m_resource ? static_cast<pointer>(m_resource->allocate(
55  n * sizeof(T), alignof(T)))
56  : pointer{nullptr};
57  if (is_contiguous && p) {
58  auto& reg = internal::MemorySpaceRegistry::GetInstance();
59  reg.add(static_cast<dart_gptr_t>(p), m_resource);
60  }
61  return p;
62  }
63 
64  void deallocate(pointer p, std::size_t n)
65  {
66  using memory_traits = dash::memory_space_traits<GlobMemType>;
67  constexpr bool is_contiguous = std::is_same<
68  typename memory_traits::memory_space_layout_tag,
70  if (m_resource && p) {
71  m_resource->deallocate(p, n * sizeof(T), alignof(T));
72  if (is_contiguous) {
73  auto& reg = internal::MemorySpaceRegistry::GetInstance();
74  reg.erase(static_cast<dart_gptr_t>(p));
75  }
76  }
77  }
78 
79  memory_resource* resource() const noexcept
80  {
81  return m_resource;
82  }
83 
84 private:
85  memory_resource* m_resource{nullptr};
86 };
87 
88 template <class T, class GlobMemType>
89 constexpr bool operator==(
92 {
93  // We pass GlobalAllocator by copy, not reference because it is just a
94  // pointer.
95  // We further define equality in terms of memory resource equality. That is,
96  // we have to compare really the pointers instead of the memory resource
97  // objects.
98  // TODO: Think again if this is the correct decision...
99  return lhs.resource() == rhs.resource();
100 }
101 } // namespace dash
102 
103 #endif
This class is a simple memory pool which holds allocates elements of size ValueType.
Definition: AllOf.h:8