Created
November 10, 2024 02:42
-
-
Save chih-chun-chang/7b9a2c0ed766e1139c37b0bf200b742d to your computer and use it in GitHub Desktop.
cuda pinned memory allocator for std::vector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cuda_runtime.h> | |
// how to use? | |
// std::vector<float, CudaHostAllocator<float>> vec; | |
template <typename T> | |
class CudaHostAllocator { | |
public: | |
using value_type = T; | |
CudaHostAllocator() = default; | |
template <class U> constexpr CudaHostAllocator( | |
const CudaHostAllocator<U>&) noexcept {} | |
T* allocate(std::size_t n) { | |
T* ptr = nullptr; | |
cudaError_t err = cudaMallocHost((void**)&ptr, n*sizeof(T)); | |
if (err != cudaSuccess) { | |
throw std::bad_alloc(); | |
} | |
return ptr; | |
} | |
void deallocate(T* ptr, std::size_t) noexcept { | |
cudaFreeHost(ptr); | |
} | |
}; | |
template <typename T, typename U> | |
bool operator==(const CudaHostAllocator<T>&, const CudaHostAllocator<U>&) { | |
return true; | |
} | |
template <typename T, typename U> | |
bool operator!=(const CudaHostAllocator<T>&, const CudaHostAllocator<U>&) { | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment