我是 CUDA C 的新手。我正在编写一个简单的数组 Add 和 Reduce,当它运行从设备复制回主机的错误检查时,我得到一个“未知错误”。我不确定错误检查器是否有问题并且没有返回正确的 cudaError 但我无法弄清楚出了什么问题......
using namespace std;
#include <iostream>
void CudaAddReduce(int *input, int *output, size_t size);
__global__ void Fill(int *fillItem);
__global__ void Add(int *input1, int *result);
__global__ void Reduce(int *intputArray, int *outputArray);
main(int argc, char *argv[])
{
const int N = 100;
int inp[N];
int outp[N];
size_t size = (N * sizeof(int));
CudaAddReduce(inp,outp,size);
cout << outp[N] << endl;
}
void CudaAddReduce(int *input, int *output, size_t size)
{
// allocate buffers to device
//input
int *d_input;
if (cudaMalloc(&d_input,size) != cudaSuccess){
cerr << cudaGetErrorString(cudaGetLastError()) << endl;
cout << "Input allocation to device" << endl;
exit(1);
}
////////////////////////////
//output
int *d_output;
if (cudaMalloc(&d_output,size) != cudaSuccess){
cerr << cudaGetErrorString(cudaGetLastError()) <<endl;
cout << "output allocation to device" << endl;
exit(1);
}
//////////////////////////////////
//copy buffers to device from host
//////////////////////////////////
//input
if (cudaMemcpy(d_input, input, size, cudaMemcpyHostToDevice) != cudaSuccess){
cerr << cudaGetErrorString(cudaGetLastError()) << endl;
cout << "Input Copy from host to device" << endl;
exit(1);
}
/////////////////////////////////
//execute device kernals
/////////////////////////////////
int numThreads = 256;
int numBlocks = 1;
//Fill Kernal
Fill<<<numBlocks,numThreads>>>(d_input);
// Add Kernal
Add<<<numBlocks,numThreads>>>(d_input,d_output);
//execute Reduce Kernal
Reduce<<<numBlocks,numThreads>>>(d_output,d_input);
cudaThreadSynchronize();
/////////////////////////////////
//copy result from device to host
/////////////////////////////////
//output
if (cudaMemcpy(output,d_output,size,cudaMemcpyDeviceToHost)!= cudaSuccess){
cerr << cudaGetErrorString(cudaGetLastError()) << endl;
cout << "Output Copy from device to host" << endl;
exit(1);
}
//clear device buffers
cudaFree(d_input);
cudaFree(d_output);
}
__global__ void Fill(int *fillItem)
{
int id = blockIdx.x * blockDim.x + threadIdx.x;
fillItem[id] = 1;
}
__global__ void Add (int *input1, int* result)
{
int id = blockIdx.x * blockDim.x + threadIdx.x;
result[id] = input1[id] + input1[id];
}
__global__ void Reduce(int *inputArray, int *outputArray)
{
extern __shared__ int sdata[];
// each thread loads one element from global to shared mem
unsigned int tid = threadIdx.x;
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
sdata[tid] = inputArray[i];
__syncthreads();
// do reduction in shared mem
for(unsigned int s=1; s < blockDim.x; s *= 2)
{
if(tid % (2*s) == 0)
{
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
// write result for this block to global mem
if(tid == 0) outputArray[blockIdx.x] = sdata[0];
}
谢谢