forked from cms-patatrack/pixeltrack-standalone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HostAllocator.h
55 lines (44 loc) · 1.42 KB
/
HostAllocator.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#ifndef HeterogeneousCore_CUDAUtilities_HostAllocator_h
#define HeterogeneousCore_CUDAUtilities_HostAllocator_h
#include <memory>
#include <new>
#include <cuda_runtime.h>
namespace cms {
namespace cuda {
class bad_alloc : public std::bad_alloc {
public:
bad_alloc(cudaError_t error) noexcept : error_(error) {}
const char* what() const noexcept override { return cudaGetErrorString(error_); }
private:
cudaError_t error_;
};
template <typename T, unsigned int FLAGS = cudaHostAllocDefault>
class HostAllocator {
public:
using value_type = T;
template <typename U>
struct rebind {
using other = HostAllocator<U, FLAGS>;
};
T* allocate(std::size_t n) const __attribute__((warn_unused_result)) __attribute__((malloc))
__attribute__((returns_nonnull)) {
void* ptr = nullptr;
cudaError_t status = cudaMallocHost(&ptr, n * sizeof(T), FLAGS);
if (status != cudaSuccess) {
throw bad_alloc(status);
}
if (ptr == nullptr) {
throw std::bad_alloc();
}
return static_cast<T*>(ptr);
}
void deallocate(T* p, std::size_t n) const {
cudaError_t status = cudaFreeHost(p);
if (status != cudaSuccess) {
throw bad_alloc(status);
}
}
};
} // namespace cuda
} // namespace cms
#endif // HeterogeneousCore_CUDAUtilities_HostAllocator_h