检测指针是否指向CUDA中的设备或主机
问题描述:
在CUDA中,是否有任何方法知道指针是指向设备或主机上的内存。检测指针是否指向CUDA中的设备或主机
一个由该运算例子是:
int *dev_c, *host_c;
cudaMalloc((void**)&dev_c, sizeof(int));
host_c = (int*) malloc(sizeof(int));
我当然可以看名字的,但在那里寻找广告指针dev_c和HOST_C,并说任何方式,HOST_C点广告主dev_c指向该设备。
答
我不认为这是可能的。指针指向内存中的某个地址,如果这是主机或设备内存,则不需要现在。当程序启动时,它可以放入(几乎)每个地址内存的操作系统,所以你不能猜测。你应该注意变量名称。
答
不是直接。一种方法是为设备指针编写一个封装类,以便明确指出设备和主机指针在代码中是不同的。您可以在Thrust模板库中看到这个想法的模型,该库有一个名为device_ptr
的类型,以清楚地描述设备和主机指针类型。
答
开始(我认为)CUDA 4和Fermi GPUs。 Nvidia支持UVA (Unified Virtual Address Space)。 功能cudaPointerGetAttributes似乎正是你要求的。请注意,我相信它只适用于分配给cudaHostAlloc(而不是c malloc)的主机指针。
答
这是一个小例子,展示了如何使用Unified Virtual Addressing来检测指针是否指向主机或设备的内存空间。正如@PrzemyslawZych指出的那样,它仅适用于分配为cudaMallocHost
的主机指针。
#include<stdio.h>
#include<cuda.h>
#include<cuda_runtime.h>
#include<assert.h>
#include<conio.h>
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
getch();
if (abort) { exit(code); getch(); }
}
}
int main() {
int* d_data;
int* data; // = (int*)malloc(16*sizeof(int));
cudaMallocHost((void **)&data,16*sizeof(int));
gpuErrchk(cudaMalloc((void**)&d_data,16*sizeof(int)));
cudaDeviceProp prop;
gpuErrchk(cudaGetDeviceProperties(&prop,0));
printf("Unified Virtual Addressing %i\n",prop.unifiedAddressing);
cudaPointerAttributes attributes;
gpuErrchk(cudaPointerGetAttributes (&attributes,d_data));
printf("Memory type for d_data %i\n",attributes.memoryType);
gpuErrchk(cudaPointerGetAttributes (&attributes,data));
printf("Memory type for data %i\n",attributes.memoryType);
getch();
return 0;
}
不幸的是,您无法判断指针是分配在主机上还是设备上。 – sgarizvi 2013-02-15 09:56:18