Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

parallel processing - (CUDA C) Why is it not printing out the value copied from device memory?

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
", a, b, c);

    return 0;
}

But when I run the program, the output is: "For a = 2, b = 7, we get a + b = -3"

meaning that the value of c was unchanged!

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code is correctly printing the value of c as 9. You need to clarify on the environment you are running this code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...