c++ - 我可以检查一个地址是否在共享内存中吗?

标签 c++ cuda gpu-shared-memory

我想编写以下 CUDA 函数:

void foo(int* a, size_t n)
{
     if ( /* MAGIC 1 */ ) {
         // a is known to be in shared memory, 
         // so use it directly
     }
     else {
         // make a copy of a in shared memory
         // and use the copy
     }
 }

在主机端,我们有一个稍微相关的设施,形式为 cudaPointerGetAttributes ,它可以告诉我们指针是指向设备内存还是主机内存;也许也有某种方法可以区分设备代码中的指针,也许它还可以区分共享指针和全局指针。或者,也许甚至更好 - 也许有一个编译时机制可以做到这一点,因为毕竟,设备功能仅编译到内核中并且不是独立的,因此 nvcc 通常可以知道它们是否是否与共享内存一起使用。

最佳答案

您可以使用isspacep PTX instruction通过一些内联“汇编”:

// First, a pointer-size-related definition, in case
// this code is being compiled in 32-bit rather than 
// 64-bit mode; if you know the code is always 64-bit
// you can just use the "l"

#if defined(_WIN64) || defined(__LP64__)
# define PTR_CONSTRAINT "l"
#else
# define PTR_CONSTRAINT "r"
#endif

__device__ int isShared(void *ptr)
{
    int res;
    asm("{"
        ".reg .pred p;\n\t"
        "isspacep.shared p, %1;\n\t"
        "selp.b32 %0, 1, 0, p;\n\t"
        "}" :
        "=r"(res): PTR_CONSTRAINT(ptr));
    return res;
}

所以你的例子就变成了

__device__ void foo(int* a, size_t n)
{
     if (isShared(a)) {
         // a is known to be in shared memory, 
         // so use it directly
     } else {
         // make a copy of a in shared memory
         // and use the copy
     }
}

关于c++ - 我可以检查一个地址是否在共享内存中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42519766/

相关文章:

c++ - 函数和仿函数作为模板函数的参数

c++ - boost/asio/ssl 抛出 "undefined reference"错误

c++ - CUDA/OGL 互操作崩溃

c++ - CUDA:使用线性化 2D 共享内存的数组中所有元素的总和

filter - CUDA 中的 2D 中值滤波 : how to efficiently copy global memory to shared memory

c++ - 具有唯一键的 multimap

c++ - 在用户键入 MFC 时验证编辑控件的文本

c - CUDA 中的多精度乘法

matrix - CUBLAS - 矩阵元素求幂可能吗?

gpu - GPU共享内存很小-我该怎么办?