我希望能够使用hbwmalloc库直接在MCDRAM上分配像Vectors这样的C ++对象。问题是只实现了C malloc。因此,我想到编写一个实现resize的Vector的子类,使用hbw_malloc进行动态分配保留。
这将允许程序员选择分配数据的NUMA节点。
这是做我想做的最好的主意吗?
答案 0 :(得分:2)
memkind library(可让您轻松访问MCDRAM)已经为您提供了C ++分配器。有关详细信息,请参阅此manual entry。
它的使用非常简单,如本例所示
#include <hbw_allocator.h>
#include <vector>
#include <assert.h>
int main(int argc, char*argv[])
{
std::vector<unsigned, hbw::allocator<unsigned> > v;
v.push_back (123);
assert(v.size() == 1);
assert(v[0] == 123);
return 0;
}
答案 1 :(得分:1)
你可以这样做:
#include <hbwmalloc.h> // hbw_check_available, hbw_malloc, hbw_free
#include <cstddef> // std::size_t
#include <cstdint> // std::intptr_t
#include <stdexcept> // std::logic_error
#include <new> // std::bad_alloc
#include <memory> // std::addressof
#define do_hbw_check_available
template <class T>
struct hbw_allocator
{
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = std::size_t;
using difference_type = std::intptr_t;
static pointer allocate(size_type n)
{
#if defined(do_hbw_check_available)
if (0 != hbw_check_available())
{
throw std::logic_error("HBW not available");
}
#endif
// Calculate size of storage with alignment and padding
const size_type size = sizeof(value_type) * n;
// Allocate storage
pointer p = hbw_malloc(size);
// Ensure that memory was in fact allocated
if (nullptr == p)
{
throw std::bad_alloc();
}
return p;
}
static void deallocate(const_pointer p, size_type /* n */)
{
hbw_free(p);
}
void construct(pointer p, const_reference t)
{
// Call copy-constructor of the element pointed to by p
new ((void*) p) value_type(t);
}
void destroy(pointer p)
{
// Call destructor of the element pointed to by p
p->~value_type();
}
size_type max_size () const
{
return size_type(-1) / sizeof(value_type);
}
bool operator!=(const hbw_allocator<value_type>& arg) const
{
return !(*this == arg);
}
// Returns true if and only if storage allocated from *this can be deallocated from other, and vice versa.
// Always returns true for stateless allocators.
bool operator==(const hbw_allocator<value_type>& /* arg */) const
{
return true;
}
pointer adress(reference arg)
{
return std::addressof(arg);
}
const_pointer adress(const_reference arg) const
{
return std::addressof(arg);
}
template <class U>
struct rebind
{
using other = hbw_allocator<U>;
};
};
示例:强>
然后使用它:
template <class T>
using hbw_vector = std::vector<T, hbw_allocator<T>>;
hbw_vector<int> vec(5);