cuda:将全局变量用于设备内存

时间:2012-01-05 15:10:44

标签: variables memory cuda global

我有一个关于如何在cuda代码中使用适当变量的问题。我的程序有很多数组,需要在不同的函数中访问,我想避免传递它们,并希望使用全局变量和2D mallocpitch数组,而不是扁平化的1D数组。所以,我在考虑这样的事情:

__device__ double * dataPtr ;
__device__ size_t dataPitch;
....
int main()
{
 double * dataPtrLoc; size_t dataPitchLoc;
cudaMallocPitch( (void**) &dataPtrLoc, &dataPitchLoc, width*sizeof(double), height);
cudaMemcpyToSymbol(dataPtr, &dataPtrLoc, sizeof(dataPtrLoc));
cudaMemcpyToSymbol(dataPitch, &dataPitchLoc, sizeof(dataPitchLoc));
...
}

看起来这是获取全球2D设备数据的好方法吗?你能提出建议吗?

编辑:我制作了这个程序,它编译并运行良好:

#include <stdio.h>
__device__ int *d_gridPtr;
__device__ size_t d_gridPitch;

__device__ int valij(int ii, int jj)
{
  int* row = (int*)((char*)d_gridPtr + ii * d_gridPitch);
  return (row[jj]);
}

__global__ void printval()
{
  int val0, val1, val2, val3;
  val0= valij(0,0);
  val1= valij(0,1);
  val2= valij(1,0);
  val3= valij(1,1);
  printf("%d %d %d %d \n", val0, val1, val2, val3);
}

int main()
{
  size_t d_gridPitchLoc;
  int * d_gridPtrLoc;  
  cudaMallocPitch((void**)&d_gridPtrLoc, &d_gridPitchLoc, 2 * sizeof(int), 2);
  cudaMemcpyToSymbol(d_gridPtr, & d_gridPtrLoc, sizeof(d_gridPtrLoc));
  cudaMemcpyToSymbol(d_gridPitch, &d_gridPitchLoc, sizeof(float));

  int h_mem[2*2]={0,1,100,4};  
  size_t hostpitch = 2* sizeof(int);
  cudaMemcpy2D(d_gridPtrLoc,d_gridPitchLoc,h_mem,hostpitch,2*sizeof(int),2,cudaMemcpyHostToDevice );

  printval<<<1,1>>> ();
  cudaDeviceReset();  
}

1 个答案:

答案 0 :(得分:1)

如果warp或块的所有线程同时访问相同的只读全局内存地址(例如数组索引),则考虑将该只读全局数据存储在__constant__内存数组中。如果您写入数据,则无法使用__constant__

如果您的数组是只读的,并且您的访问模式具有强大的2D局部性(在warp和/或块中),请考虑使用纹理。