【问题标题】:Subtracting two integers causes integer-underflow in device code减去两个整数会导致设备代码中的整数下溢
【发布时间】:2019-02-01 18:37:57
【问题描述】:

在我的 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++ cuda integer-overflow nvcc underflow


    【解决方案1】:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多