变量前缀__device__以及__managed__

1.__device__

作为变量前缀时,__device__限定符声明位于设备上的变量。如果此限定符单独使用,则变量具有以下特征:

  a.位于全局存储器空间中;

  b.与应用程序具有相同的生命周期;

可通过Grid内的所有线程访问,也可以通过runtime库从主机访问。

2.__managed__

作为变量前缀时,__managed__限定符声明位于managed memory上的变量。这样的变量在设备和主机上都能引用及操作。

 

范例代码如下:

#include<stdio.h>
#include <malloc.h>


int a[4][4];
__device__ int dev_a[4][4];

__device__ __managed__ int result;

__global__ void show()
{
    for(int i=0;i<4;i++)
        for(int j=0;j<4;j++)
            dev_a[i][j]=i+j;
    result=dev_a[1][2]+dev_a[2][3];
}



int main()
{
    for(int i=0;i<4;i++)
        for(int j=0;j<4;j++)
            a[i][j]=i+j;
    printf("the result should be:%d\n",a[1][2]+a[2][3]);
    
    show<<<1,1>>>();
    cudaDeviceSynchronize();
    
    printf("the result is %d\n",result);
    
    return 0;
}

 

结果为:

the result should be:8

the result is 8

posted @ 2019-03-22 15:31  March01  阅读(898)  评论(0编辑  收藏  举报