我不知道为什么我的内核函数不起作用。理论上我的程序应该显示 a = 14,但它显示 a = 5。
#include <iostream>
#include <cuda.h>
#include <cuda_runtime.h>
using namespace std;
__global__ void AddIntCUDA(int* a, int* b)
{
a[0] += b[0];
}
int main()
{
int a = 5;
int b = 9;
int *d_a ;
int *d_b ;
cudaMalloc(&d_a, sizeof(int));
cudaMalloc(&d_b, sizeof(int));
cudaMemcpy(d_a, &a, sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &b, sizeof(int), cudaMemcpyHostToDevice);
AddIntCUDA<<<1, 1>>>(d_a, d_b);
cudaMemcpy(&a, d_a, sizeof(int), cudaMemcpyDeviceToHost);
cout<<"The answer is a = "<<a<<endl;
cudaFree(d_a);
cudaFree(d_b);
return 0;
}
我也不明白为什么如果我有:
cudaMemcpy(d_b, &b, sizeof(int), cudaMemcpyHostToDevice); //d_b = 9 on device
cudaMemcpy(&a, d_b, sizeof(int), cudaMemcpyDeviceToHost); //a = 9 on host
a 还是 5?