我从CUDA编程开始,作为实现粒子积分器的开始,我制作了一个积分器类,该类保存有关粒子的数据并且应该能够对其进行集成。数据来自另一个容器类,我想在统一内存上分配此数据。为此,我有一个成员函数'_allocate',它所做的只是为成员变量调用cudaMallocManaged。现在,我想知道应该使用哪种功能关键字包装该功能。
我读到您不能在类定义中使用'global',现在我正在同时使用主机和设备,因为主机和设备都应该可以使用统一内存,但是我不确定这是否正确方式。
这是我要在其中实现的类:
template <typename T>
class Leapfrog : public Integrator<T> {
public:
...
private:
T *positions;
T *masses;
T *velocities;
T *types;
__device__ __host__ bool _allocate();
__device__ __host__ bool _free();
__device__ __host__ bool _load_data();
};
// allocates space on the unified memory for the
// private variables positions, masses, velocities, types
template <typename T>
__host__ __device__ void Leapfrog<T>::_allocate(){
cudaMallocManaged(&positions, particleset.N*3*sizeof(T));
cudaMallocManaged(&masses, particleset.N*sizeof(T));
cudaMallocManaged(&velocities, particleset.N*3*sizeof(T));
cudaMallocManaged(&types, particleset.N*sizeof(T));
}
我不知道这是否与功能关键字相关,但我还想在分配后检查cudaError,以查看是否成功
答案 0 :(得分:0)
每个只能在设备上调用的可调用对象,应使用__device__
修饰。并且如果仅主机应使用__host__
装饰。
__host__ __device__
仅用于将在主机和设备上都被调用的可呼叫对象。
cudaMallocManaged
是仅主机代码:
__host__cudaError_t cudaMallocManaged ( void** devPtr, size_t size, unsigned int flags = cudaMemAttachGlobal )
Allocates memory that will be automatically managed by the Unified Memory system.
所以您的代码只能在主机上工作。