(CUDA C)为什么不打印出从设备存储器复制的值? [英] (CUDA C) Why is it not printing out the value copied from device memory?
本文介绍了(CUDA C)为什么不打印出从设备存储器复制的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我现在正在通过NVIDIA提供的培训幻灯片学习CUDA.他们有一个示例程序,显示了如何将两个整数相加.代码如下:
I'm learning CUDA right now through the training slides provided by NVIDIA. They have a sample program that shows how you could add two integers. The code is below:
#include <stdio.h>
__global__ void add(int *a, int *b, int *c) {
*c = *a+*b;
}
int main(void) {
int a, b, c; // Host copies of a, b, c
int *d_a, *d_b, *d_c; // Device copies of a, b, c
size_t size = sizeof(int);
//Allocate space for device copies of a, b, c
cudaMalloc((void**)&d_a, size);
cudaMalloc((void**)&d_b, size);
cudaMalloc((void**)&d_c, size);
//Setup input values
a = 2;
b = 7;
c = -3;
//Copy inputs to device
cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);
//Launch add() kernel on GPU
add<<<1,1>>>(d_a, d_b, d_c);
//Copy result back to host
cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost);
//Cleanup
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
printf("For a = %d, b = %d, we get a + b = %d\n", a, b, c);
return 0;
}
但是当我运行程序时,输出为: 对于a = 2,b = 7,我们得到a + b = -3"
But when I run the program, the output is: "For a = 2, b = 7, we get a + b = -3"
表示c的值不变!
我在做什么错了?
推荐答案
您的代码正确地将c的值打印为9.您需要弄清正在运行此代码的环境.
Your code is correctly printing the value of c as 9. You need to clarify on the environment you are running this code.
这篇关于(CUDA C)为什么不打印出从设备存储器复制的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文