cuda 内核函数中的 for 循环给出错误的值

问题描述 投票:0回答:1

我有一些带有 2d 内核函数的 cuda 代码,如下所示:

#include <stdio.h>
#include <stdlib.h>

#include <cuda_runtime.h>
#include <device_launch_parameters.h>

#define row 65
#define col 13824

__global__ void tt(int *pp){
    int i = blockDim.x * blockIdx.x + threadIdx.x;
    int j = blockDim.y * blockIdx.y + threadIdx.y;

    for(unsigned ig=0;ig<33;ig++){
        pp[i*col+j]+=1;
    }
    return;
}

int main(){

    int *pp;
    int *rr;

    pp=(int*)malloc(sizeof(int)*col*row);
    rr=(int*)malloc(sizeof(int)*col*row);

    memset(pp,0,sizeof(int)*row*col);

    int *pp_g;
    cudaMalloc((void**)&pp_g,sizeof(int)*row*col);
    cudaMemcpy(pp_g,pp,sizeof(int)*row*col,cudaMemcpyHostToDevice);

    dim3 block(32,32,1);
    dim3 grid(row/32+1,col/32+1,1);

    tt<<<grid,block>>>(pp_g);
    cudaDeviceSynchronize();

    cudaMemcpy(rr,pp_g,sizeof(int)*row*col,cudaMemcpyDeviceToHost);

    int ct=0;
    for(unsigned i=0;i<row*col;i++){
        if(rr[i]!=33){
            //printf("%d\n",rr[i]);
            ct++;
        }
        //printf("%d\n",rr[i]);
    }
    printf("%d\n",ct);

    return 0;

}

rr数组中的例外结果应该都是33,然而实际结果都是0。但是当我将块和网格更改为

block(8,8,1)
grid(row/8+1,col/8+1,1)
时,
rr
数组中的一些结果变得正确,但仍然存在
rr
数组中有 512 个错误结果为 0。

我无法弄清楚我的代码有什么问题。我想知道我的结果发生了什么。

c++ cuda cuda-gdb
1个回答
-2
投票

内核线程在

i >= row
j >= col
时执行非法内存访问。 此外,当
i >= row
j < col
时,线程与“合法”线程同时执行内存写入。

检查 CUDA 错误将有助于您理解问题。请参阅这篇文章

© www.soinside.com 2019 - 2024. All rights reserved.