首页 > 解决方案 > 减去两个整数会导致设备代码中的整数下溢

问题描述

在我的 cuda 设备代码中,我正在检查我减去线程的 id 和 blockDim 以查看天气或我可能想要使用的数据是否在范围内。但是当这个数字低于 0 时,它似乎又回到了最大值。

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

float input[] =
{
1.5f, 2.5f, 3.5f,
4.5f, 5.5f, 6.5f,
7.5f, 8.5f, 9.5f,
};

__global__ void underflowCausingFunction(float* in, float* out)
{
    int id = (blockDim.x * blockIdx.x) + threadIdx.x;
    out[id] = id - blockDim.x;
}

int main()
{
    float* in;
    float* out;

    cudaMalloc(&in, sizeof(float) * 9);
    cudaMemcpy(in, input, sizeof(float) * 9, cudaMemcpyHostToDevice);
    cudaMalloc(&out, sizeof(float) * 9);

    underflowCausingFunction<<<3, 3>>>(in, out);

    float recivedOut[9];
    cudaMemcpy(recivedOut, out, sizeof(float) * 9, cudaMemcpyDeviceToHost);

    cudaDeviceSynchronize();

    std::cout << recivedOut[0] << " " << recivedOut[1] << " " << recivedOut[2] << "\n"
    << recivedOut[3] << " " << recivedOut[4] << " "  << recivedOut[5] << "\n"
    << recivedOut[6] << " " << recivedOut[7] <<  " " << recivedOut[8] << "\n";

     cudaFree(in);
     cudaFree(out);

     std::cin.get();
}

这个的输出是:

4.29497e+09 4.29497e+09 4.29497e+09
0 1 2
3 4 5

我不确定为什么它表现得像一个无符号整数。如果相关,我使用的是 GTX 970 和 Visual Studio 插件附带的 NVCC 编译器。如果有人可以解释正在发生的事情或我做错了什么,那就太好了。

标签: c++cudainteger-overflownvccunderflow

解决方案


内置变量如threadIdxblockIdx无符号数量组成

在 C++ 中,当您从有符号整数量中减去无符号量时:

out[id] = id - blockDim.x;

执行的算术是无符号算术

既然你想要有符号的算术(显然)正确的做法是确保两个被减去的量都是有符号的类型(让我们int在这种情况下使用):

out[id] = id - (int)blockDim.x;

推荐阅读