基本CUDA代码的奇怪行为.

smi*_*dha 1 c cuda

我无法理解以下简单CUDA代码的输出.代码所做的就是分配两个整数数组:一个在主机上,一个在设备上,每个都是16号.然后将设备数组元素设置为整数值3,然后将这些值复制到host_array中,其中所有元素都是然后打印出来.

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
  int num_elements = 16;
  int num_bytes = num_elements * sizeof(int);

  int *device_array = 0;
  int *host_array = 0;

  // malloc host memory
  host_array = (int*)malloc(num_bytes);

  // cudaMalloc device memory
  cudaMalloc((void**)&device_array, num_bytes);

  // Constant out the device array with cudaMemset
  cudaMemset(device_array, 3, num_bytes);

  // copy the contents of the device array to the host
  cudaMemcpy(host_array, device_array, num_bytes, cudaMemcpyDeviceToHost);

  // print out the result element by element
  for(int i = 0; i < num_elements; ++i)
    printf("%i\n", *(host_array+i));

  // use free to deallocate the host array
  free(host_array);

  // use cudaFree to deallocate the device array
  cudaFree(device_array);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

该程序的输出是50529027逐行打印16次.

50529027
50529027
50529027
..
..
..
50529027
50529027
Run Code Online (Sandbox Code Playgroud)

这个号码来自哪里?当我在cudaMemset调用中将0替换为0时, 我得到了正确的行为.即0行逐行打印16次.

nvcc test.cu在使用CUDA 4.0的Ubuntu 10.10上编译了代码

Chr*_*Wue 7

我不是cuda专家,但50529027是十六进制的0x03030303.这意味着cudaMemsetbyte数组中的每个设置为3而不是每个int.鉴于cuda memset的签名(传递要设置的字节数)和memset操作的一般语义,这并不奇怪.

编辑:至于你(我猜)如何实现你想要的隐含问题我认为你必须编写一个循环并初始化每个数组元素.