Cuda重用共享内存变量名

时间:2013-10-12 20:06:43

标签: memory cuda shared

我有两个运行的cuda内核,一个接一个地运行:

__global__
void calculate_histo(const float* const d_logLuminance,
        unsigned int* d_histogram,
        float min_logLum,
        float lumRange,
        int numBins,
        int num_elements){
    extern __shared__ float sdata[];
    int tid = threadIdx.x;
    int bid = blockIdx.x;
    int gid = tid * blockDim.x + bid;

    // load input into __shared__ memory
    if(gid < num_elements)
    {
        sdata[tid] = d_logLuminance[gid];
        __syncthreads();

        //compute bin value of input
        int bin = static_cast <int> (floor((d_logLuminance[gid]-min_logLum)/ lumRange * numBins));
        //increment histogram at bin value
        atomicAdd(&(d_histogram[bin]), 1);
    }
}

__global__
void blelloch_scan(unsigned int* const d_cdf, unsigned int* d_histogram, int numBins) {
    extern __shared__ unsigned int sdata[];// allocated on invocation
    int thid = threadIdx.x;
    //printf("%i \n", thid);
    //printf("%i \n", d_histogram[thid]);

    int offset = 1;


    sdata[2*thid] = d_histogram[2*thid]; // load input into shared memory
    sdata[2*thid+1] = d_histogram[2*thid+1];

    // build sum in place up the tree
    for (int d = numBins>>1; d > 0; d >>= 1) {
        __syncthreads();
        if (thid < d) {
            int ai = offset*(2*thid+1)-1;
            int bi = offset*(2*thid+2)-1;
            sdata[bi] += sdata[ai];
        }
        offset *= 2;
    }
    if (thid == 0) { sdata[numBins - 1] = 0; } // clear the last element
    // traverse down tree & build scan
    for (int d = 1; d < numBins; d *= 2) {
        offset >>= 1;
        __syncthreads();
        if (thid < d) {
            int ai = offset*(2*thid+1)-1;
            int bi = offset*(2*thid+2)-1;
            float t = sdata[ai];
            sdata[ai] = sdata[bi];
            sdata[bi] += t;
        }
        __syncthreads();
        d_cdf[2*thid] = sdata[2*thid]; // write results to device memory
        d_cdf[2*thid+1] = sdata[2*thid+1];
    }

}

他们都使用共享内存。第二个有一个unsigned int数组作为共享内存。第一个有一个浮点数组。我以为我应该能够为两个数组重用相同的变量名sdata,因为每次内核启动后都会清除共享内存,但是我收到了错误:

declaration is incompatible with previous 'sdata'

如果我为每个内核使用不同的变量名,那似乎可以解决问题。任何人都知道为什么我不能重用相同的变量名称?

1 个答案:

答案 0 :(得分:1)

CUDA只是遵循标准C语言的规则。引用Kernighan和Ritchie的“The C Programming Language”一书:

  

外部变量必须在任何函数之外定义一次;这为它预留了存储空间。必须在每个想要访问它的函数中声明变量;这说明了变量的类型。 [...] 定义是指创建变量或分配存储的位置; 声明指的是声明变量性质但没有分配存储空间的地方。

在你的程序的某个地方你应该有类似

的东西
extern __shared__ unsigned int sdata[];

在该位置,您创建指针sdataunsigned int。在__global__函数中,您声明 sdata的类型,以便__global__函数可以知道它。在

kernel<<<blocks,threads,numbytes_for_shared>>>(...);

启动,您将分配sdata指向的数组的空间。