正如您所发现的,您的错误处理方法不起作用。下面我粘贴了您的代码版本,其中包含我经常使用的错误检查方法。在您的故障点处无法正常工作的原因是您的网格大小(您正在启动一维网格)超过了 X 维度中的最大网格大小(默认情况下为 65535,即计算能力高达 2.x)。如果你想利用更大的网格尺寸(2^31 -1 是计算能力 3.0 的限制),你需要使用-arch=sm_30
转变。
这里仅供参考的是您的代码版本,其中显示了我经常使用的错误检查方法。
#include <stdio.h>
#include <fstream>
#define cudaCheckErrors(msg) \
do { \
cudaError_t __err = cudaGetLastError(); \
if (__err != cudaSuccess) { \
fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \
msg, cudaGetErrorString(__err), \
__FILE__, __LINE__); \
fprintf(stderr, "*** FAILED - ABORTING\n"); \
exit(1); \
} \
} while (0)
__global__ void addKernel(float* _Results, int _TotalCombinations)
{
// Get thread Id
unsigned int Id = (blockDim.x * blockDim.y * blockIdx.x) + (blockDim.x * threadIdx.y) + threadIdx.x;
//If the Id is within simulation range, log it
if(Id < _TotalCombinations)
{
_Results[Id] = 0.95f;
}
}
#define BLOCK_DIM_X 32
#define BLOCK_DIM_Y 32
#define BLOCK_SIZE BLOCK_DIM_X * BLOCK_DIM_Y // Statc block size of 32*32 (1024)
int main()
{
// The number of simulations to run
unsigned int totalCombinations = 65000000;
int gridsize = 1;
// Work out how many blocks of size 1024 are required to perform all of totalCombinations
for(unsigned int totalsize = gridsize * BLOCK_SIZE; totalsize < totalCombinations;
gridsize++, totalsize = gridsize * BLOCK_SIZE)
;
printf("gridsize = %d, blocksize = %d\n", gridsize, BLOCK_SIZE);
// Allocate host memory
float* host_results = new float[totalCombinations];
memset(host_results, 0, sizeof(float) * totalCombinations);
float *dev_results = 0;
cudaSetDevice(0);
// Allocate device memory
cudaMalloc((void**)&dev_results, totalCombinations * sizeof(float));
cudaCheckErrors("cudaMalloc fail");
dim3 grid, block;
block = dim3(BLOCK_DIM_X, BLOCK_DIM_Y);
grid = dim3(gridsize);
// Launch kernel
addKernel<<<gridsize, block>>>(dev_results, totalCombinations);
cudaCheckErrors("kernel fail");
// Wait for synchronize
cudaDeviceSynchronize();
cudaCheckErrors("sync fail");
// Copy device data back to host
cudaMemcpy(host_results, dev_results, totalCombinations * sizeof(float), cudaMemcpyDeviceToHost);
cudaCheckErrors("cudaMemcpy 2 fail");
double total = 0.0;
// Total the results in the host array
for(unsigned int i = 0; i < totalCombinations; i++)
total+=host_results[i];
// Print results to screen
printf("Total %f\n", total);
delete[] host_results;
return 0;
}