在CUDA中检测指针是否指向设备或主机

11
在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指向设备呢?


2
很遗憾,您无法确定指针是在主机上分配还是在设备上分配。 - sgarizvi
4个回答

9

我认为这是关于CUDA 4和Fermi GPUs的信息。Nvidia支持UVA(统一虚拟地址空间)(Unified Virtual Address Space)。 函数cudaPointerGetAttributes似乎完全符合您的要求。请注意,我认为它仅适用于使用cudaHostAlloc(而不是c malloc)分配的主机指针。


6
这是一个小例子,展示了如何使用统一虚拟寻址来检测指针是否指向主机或设备内存空间。正如@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;
}

2
看起来是可能的:以下示例显示使用cudaPointerGetAttributes分配了一个带有newarray,以确定它不驻留在GPU上(通过返回错误)。 https://github.com/scikit-hep/awkward-1.0/blob/3909e8e6ee27a3da49056c5f71b863829e8c8ff4/studies/cuda_studies/src/study_1.cu#L51-L57 - Jim Pivarski

3

不能直接这样做。一种方法是编写一个封装设备指针的类,以便在代码中明确表明设备指针和主机指针是不同的。您可以在Thrust模板库中看到此思想的模型,其中有一种类型称为device_ptr,以清晰地划分设备和主机指针类型。


0

我认为这是不可能的。指针指向内存中的某个地址,你不知道这是主机还是设备内存。当程序启动时,它可以被放置在操作系统内存的(几乎)任何地址上,因此你不能猜测。你应该注意变量名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接