【问题标题】:CUDA - copy a struct with an array to the gpu and backCUDA - 将带有数组的结构复制到 gpu 并返回
【发布时间】:2016-08-30 13:09:54
【问题描述】:

我将八叉树的节点存储在一个数组中,并且 pos_childs 指向子节点所在的数组位置。如何将这样的结构获取到 gpu,访问它并正确地从 gpu 中取回它?由于硬件限制,我无法使用统一内存。

typedef struct Octree
{
    //data
    unsigned pos_childs[8];
}octree_t;

【问题讨论】:

    标签: arrays struct cuda


    【解决方案1】:

    处理包含动态分配数据的嵌入指针的结构数组与处理基本类型数组没有太大区别。

    这是一个工作示例,显示了在主机上初始化、传递给设备、在设备上修改并返回给主机的结构数组:

    $ cat t690.cu
    #include <iostream>
    
    const int dsize = 5;
    const int nTPB = 256;
    
    typedef struct Octree
    {
        //data
        unsigned pos_childs[8];
    }octree_t;
    
    
    __global__ void kernel(Octree *data, size_t n){
    
      int idx=threadIdx.x+blockDim.x*blockIdx.x;
      if (idx < n)
        data[idx].pos_childs[4] = data[idx].pos_childs[3];
    }
    
    
    int main(){
    
      Octree *h_data, *d_data;
      h_data = new Octree[dsize];
      cudaMalloc(&d_data, dsize*sizeof(Octree));
      for (int i = 0; i < dsize; i++) {h_data[i].pos_childs[3] = i; h_data[i].pos_childs[4] = 0;}
      cudaMemcpy(d_data, h_data, dsize*sizeof(Octree), cudaMemcpyHostToDevice);
      kernel<<<(dsize+nTPB-1)/nTPB,nTPB>>>(d_data, dsize);
      cudaMemcpy(h_data, d_data, dsize*sizeof(Octree), cudaMemcpyDeviceToHost);
      for (int i = 0; i < dsize; i++) std::cout << h_data[i].pos_childs[4] << " ";
      std::cout << std::endl;
      return 0;
    }
    
    $ nvcc -o t690 t690.cu
    $ cuda-memcheck ./t690
    ========= CUDA-MEMCHECK
    0 1 2 3 4
    ========= ERROR SUMMARY: 0 errors
    $
    

    【讨论】:

    • 谢谢,这对我帮助很大。
    猜你喜欢
    • 1970-01-01
    • 2012-11-09
    • 2015-03-11
    • 2014-05-14
    • 2017-08-27
    • 2012-03-27
    • 2021-06-07
    • 2015-01-06
    • 2019-06-16
    相关资源
    最近更新 更多