首页 > 解决方案 > 可以将短裤数组传递到 CUDA 内核中吗

问题描述

我已经编写了一个 CUDA 内核,当我将一个短裤数组复制到设备内存然后将其传递给内核时它不起作用。下面的简化代码表达了我的问题。

KernelCaller()
{
    const int size = 1;
    short hostArray[size]{41};
    short* devPointer;
    cudaMalloc((void**)&devicePointer, size * sizeof(short));
    cudaMemcpy(devPointer, hostArray, size * sizeof(short), cudaMemcpyHostToDevice);
    cudaKernel<<<1,1>>>(devPointer);

}

__global__
void cudaKernel(short* arr)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    short val = arr[idx];
}

此时的值为val1063714857,我希望它是 41。我假设问题是十六进制的 41 是 0x29,而我的值是 0x3F670029,所以看起来它读取了太多字节,因为 0x29 位于开始。当我切换到一个浮点数组时,它工作得很好,但我试图节省内存。CUDA 不允许一系列短裤吗?

标签: cuda

解决方案


我已经实现了您的代码并按预期获得了输出。

这是代码

 #include<stdio.h>
__global__ void cudaKernel(short* arr)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    short val = arr[idx];
    # if __CUDA_ARCH__>=200
        printf("Inside kernel %d\n",val);
    #endif
    arr[idx] = val;
}

int main()
{
    const int size = 1;
    short hostArray[size]{41};
    printf("Before kernel call %d\n",hostArray[0]);
    short *devPointer;
    cudaMalloc((void**)&devPointer, size * sizeof(short));
    cudaMemcpy(devPointer, hostArray, size * sizeof(short), cudaMemcpyHostToDevice);
    cudaKernel<<<1,1>>>(devPointer);
    cudaMemcpy(hostArray, devPointer, size * sizeof(short), cudaMemcpyDeviceToHost);
    printf("After kernel call %d\n",hostArray[0]);
    cudaFree(devPointer);
    return 0;
}

输出是

Before kernel call 41
Inside kernel 41
After kernel call 41

所以,是的,我们可以将短裤数组传递给 CUDA 内核。


推荐阅读