减去两个整数会导致设备代码中的整数下溢

时间:2019-02-01 18:37:58

标签: c++ cuda integer-overflow nvcc underflow

在我的cuda设备代码中,我正在做一个检查,在其中减去线程的ID和blockDim来查看天气是否是我可能要使用的数据在范围内。但是当这个数字降到0以下时,它似乎又回绕到了max。

#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编译器。如果有人可以解释正在发生的事情或我在做错的事情,那将是很好的。

1 个答案:

答案 0 :(得分:5)

threadIdxblockIdx之类的内置变量为composed of unsigned quantities

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

out[id] = id - blockDim.x;

arithmetic that gets performed is unsigned arithmetic

由于(显然)您要进行有符号算术运算,因此正确的做法是确保两个相减的量均为有符号类型(在这种情况下,请使用int):

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