我是库达的新手。我正在尝试在内核中添加数组的浮点元素,但最终结果是错误的。因为我需要以原子方式进行,但另一方面 atomicAdd 仅用于整数......有什么想法吗?
__global__ void add_element(float *my_array, float *result_sum){
int tid = blockIdx.x * blockDim.x + threadIdx.x;
*result_sum += my_array[tid];
}
int main(int argc, char** argv){
float my_array[10];
float result_sum = 0;
float *device_array, *device_sum;
cudaMalloc((void**)&device_array, 10*sizeof(float) );
cudaMalloc((void**)&device_sum, sizeof(float) );
// fill the array
for (int i=0; i<10; i++){
my_array[i] = (float)i/2;
}
cudaMemcpy(device_array, my_array, 10*sizeof(float),cudaMemcpyHostToDevice);
cudaMemcpy(device_sum, &result_sum, sizeof(float),cudaMemcpyHostToDevice);
add_element<<<1,10>>>(device_array, device_sum);
cudaMemcpy(&result_sum, device_sum, sizeof(float), cudaMemcpyDeviceToHost);
for(int i=0; i<10; i++){
printf(" %f \n", my_array[i]);
}
printf("+\n----------\n %f\n", result_sum);
cudaFree(device_array);
cudaFree(device_sum);
return 0;
}