封装 CUDA 内核的最佳方法是什么?
What's the best way of encapsulating CUDA kernels?
我正在尝试使CUDA项目尽可能接近OO设计。目前,我找到的解决方案是使用 Struct 封装数据,对于需要一些 GPU 处理的每种方法,需要实现 3 个函数:
- 对象将调用的方法。
- 一个 __global__ 函数,它将调用该结构的 __device__ 方法。
- 结构内的 __device__ 方法。
我举个例子。假设我需要实现一个方法来初始化结构内的缓冲区。它看起来像这样:
struct Foo
{
float *buffer;
short2 buffer_resolution_;
short2 block_size_;
__device__ initBuffer()
{
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
int plain_index = (y * buffer_resolution.x) + x;
if(plain_index < buffer_size)
buffer[plain_index] = 0;
}
void init(const short2 &buffer_resolution, const short2 &block_size)
{
buffer_resolution_ = buffer_resolution;
block_size_ = block_size;
//EDIT1 - Added the cudaMalloc
cudaMalloc((void **)&buffer_, buffer_resolution.x * buffer_resolution.y);
dim3 threadsPerBlock(block_size.x, block_size.y);
dim3 blocksPerGrid(buffer_resolution.x/threadsPerBlock.x, buffer_resolution.y/threadsPerBlock.y)
initFooKernel<<<blocksPerGrid, threadsPerBlock>>>(this);
}
}
__global__ initFooKernel(Foo *foo)
{
foo->initBuffer();
}
我需要这样做,因为看起来我无法在结构中声明 __global__。我通过查看一些开源项目学到了这种方式,但是实现三个函数来实现每个封装的GPU方法看起来很麻烦。所以,我的问题是:这是最好的/唯一的方法吗?这甚至是一个有效的废话吗?
编辑1:在调用initFooKernel之前,我忘了放置cudaMalloc来分配缓冲区。修复了它。
目标是制作使用 CUDA 的类,同时从外面看起来像普通类?
如果是这样,为了扩展 O'Conbhui 所说的内容,您可以为 CUDA 功能创建 C 样式调用,然后创建一个包装这些调用的类。
因此,在 .cu 文件中,您将放置纹理引用、内核、调用内核的 C 样式函数以及分配和释放 GPU 内存的 C 样式函数的定义。在您的示例中,这将包括一个调用初始化 GPU 内存的内核的函数。
然后,在相应的.cpp文件中,导入一个标头,其中包含 .cu 文件中函数的声明,并定义类。在构造函数中,您可以调用分配 CUDA 内存并设置其他 CUDA 资源(例如纹理)的 .cu 函数,包括您自己的内存初始化函数。在析构函数中,调用释放 CUDA 资源的函数。在成员函数中,调用调用内核的函数。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 通过JNI传递数据数组的最快方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 在C++中包含原型文件的正确方法是什么?
- 在 OpenCV C++ 中估计基本矩阵之前对相应点进行归一化的正确方法是什么?
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 将一系列整数放入类的最佳方法是什么?
- 从长整整转换为uint64_t的推荐方法是什么?
- 将此布尔值传递给此函数的最有效方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?