Lii*_*iht -2 c++ cuda integer-overflow underflow nvcc
在我的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();
}
Run Code Online (Sandbox Code Playgroud)
这个输出是:
4.29497e+09 4.29497e+09 4.29497e+09
0 1 2
3 4 5
Run Code Online (Sandbox Code Playgroud)
我不确定为什么它表现得像一个unsigned int.如果它是相关的我使用的是GTX 970和visual studio插件附带的NVCC编译器.如果有人可以解释正在发生的事情,或者我正在做的错误,这将是伟大的.
像内置的变量threadIdx和blockIdx正在由无符号的数量.
在C++中,当您从有符号整数量中减去无符号数量时:
out[id] = id - blockDim.x;
Run Code Online (Sandbox Code Playgroud)
既然你想要签名算术(显然),要做的就是确保减去的两个数量都是带符号的类型(int在这种情况下让我们使用):
out[id] = id - (int)blockDim.x;
Run Code Online (Sandbox Code Playgroud)