c++ - 与 CUDA 并行传输数组

标签 c++ c arrays cuda

我在这里用 CUDA C 编写了一些非常简单的 GPU 代码,用于将数组 nums 复制到数组 vals 中。数字是 [4,7,1,9,2]。这就是我想复制每个元素的方式:

__global__ void makeArray(int*);

int main()
{
  int* d_nums;
  int nums[5];

  nums[0] = 4;
  nums[1] = 7;
  nums[2] = 1;
  nums[3] = 9;
  nums[4] = 2;
  cudaMalloc(&d_nums, sizeof(int)*5);

  makeArray<<<2,16>>>(d_nums);

  cudaMemcpy(nums, d_nums, sizeof(int)*5, cudaMemcpyDeviceToHost);

  for (int i = 0; i < 5; i++)
    cout << i << " " << nums[i] << endl;

  return 0;
}

__global__ void makeArray(int* nums)
{
  int vals[5];
  int threadIndex = blockIdx.x * blockDim.x + threadIdx.x;

  vals[threadIndex%5] = nums[threadIndex%5];
  __syncthreads();

  if (threadIndex < 5)
    nums[threadIndex] = vals[threadIndex];
}

从长远来看,我想使用这种方法将一个数组从 CPU 传输到 GPU 共享内存,但我什至无法让这个简单的练习文件工作。我希望输出看起来像这样:

0 4
1 7
2 1
3 9
4 2

但是我得到了这个:

0 219545856
1 219546112
2 219546368
3 219546624
4 219546880

我的想法是,通过使用大于该数组中元素数的线程索引的模数,我可以覆盖所有 5 个数据点,而不用担心过度读取数组。我还可以同时分配每个数组点,每个线程一个,然后在最后分配 __syncthreads() 以确保每个线程都完成复制。显然,这是行不通的。帮助!

最佳答案

编辑后,我们可以看到 d_nums 指向未初始化的内存。你只是分配了它,并没有填充任何东西。如果你想让 GPU 访问数据,你必须复制它:

cudaMemcpy(d_nums, nums, sizeof(nums), cudaMemcpyHostToDevice);

运行内核之前。

关于c++ - 与 CUDA 并行传输数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24186033/

相关文章:

C++ 错误 : 'x' is not a constant expression, 如何修复?

c++ - 如何在 linux 上编译 C++ 以制作 windows 二进制文件

javascript - 如何在 JS 对象中获取父属性?

php - 使用PHP的“Notice: Undefined variable”,“Notice: Undefined index”和“Notice: Undefined offset”

c++ - 在yaml-cpp中是否可以获取文档中的顶级键名称

c - 在C中: having trouble with header files and compiling the main function

c - 评估字符串和数组 - C

c - 优化递归计数算法

arrays - 具有数组公式的列中的可编辑单元格

c++ - 从 base64 C++ 解码和保存图像文件