【问题标题】:Error in simple reduce on CUDACUDA 上的简单减少错误
【发布时间】:2016-02-04 00:08:36
【问题描述】:

我是 CUDA C 的新手...我想在 1 个块中对数组元素(使用 reduce)求和,并且 267 个线程使用共享内存。我读了一本书“以CUDA为例,GPU编程的通用介绍”。根据她的一些建议,我编写了我的程序版本:

__global__ void
conva(int* a, int* out) 
{
    __shared__ int cache[534];
    int cacheIndex = threadIdx.x;
    for(int n=0; n<2;++n) {
        cache[cacheIndex+n] = a[cacheIndex+n];
        int i = blockDim.x/2;
        while (i != 0) {
            if (cacheIndex < i)
                cache[cacheIndex + n] += cache[cacheIndex + n + i];
            __syncthreads();
            i /= 2;
        } 
    }
    //need or not this __syncthreads(), I don't know
    __syncthreads();
     if (cacheIndex == 0)
         out = &cache[0];
}

int main(int argc, char** argv)
{
    //enter array for sum
    int convolution[534];
    for(int i=0; i<534; ++i) 
        convolution[i] = 1;
    //variable in which we take a sum from device
    int summa = 0;
    //it we copy on device from host
    int* tash;

    int* convolution_gpu;
    cudaMalloc((void**)(&convolution_gpu), 534*sizeof(int));
    cudaMalloc((void**)(&tash), sizeof(int));

    cudaMemcpy(convolution_gpu, convolution, 534*sizeof(int),  cudaMemcpyHostToDevice );
    //call core with 1 block and 267 threads
    conva<<<1, 267>>>(convolution_gpu, tash);

    cudaMemcpy(&summa, tash, sizeof(int), cudaMemcpyDeviceToHost);
    //and here I want 534 but I have garbage(may be)
    std::cout<<summa<<std::endl;

    cudaFree(convolution_gpu);
    cudaFree(tash);
    getchar();
}

请告诉我这里是哪里错误并帮助我解决她... (对不起我的英语)

【问题讨论】:

  • 这里不是运行时错误,只是结果中的错误

标签: cuda gpu nvidia


【解决方案1】:

在你的内核中,这个:

 if (cacheIndex == 0)
     out = &cache[0];

几乎肯定是错误的。当然你想要这样的东西:

 if (cacheIndex == 0)
     *out = cache[0];

【讨论】:

  • 您的缩减代码还有其他几个问题。 (例如,您正在启动奇数个线程,而您的缩减方法无法处理奇数线程块大小)。该方法对我来说没有意义,而且我认为它不会特别有效,因此我建议您学习 this material 减少,以了解如何做一个快速/高效的方法。
猜你喜欢
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
  • 2015-09-16
  • 2014-09-11
  • 2018-04-15
相关资源
最近更新 更多