[英]Why AddVector CUDA c++ is not working?
我試圖使用CUDA添加2個數組,但它不起作用。
我做了所有應該做的事情:
1)我並行化了VectorAdd函數
2)我將內存分配給GPu並將數據移動到GPU
3)最后我修改了函數VectorAdd以在GPU上運行
這是代碼:
#define SIZE 1024
__global__ void VectorAdd(int *a, int *b, int *c, int n)
{
int i = threadIdx.x ;
if(i < n)
c[i] = a[i] + b[i];
}
int main()
{
int *a , *b , *c;
int *d_a , *d_b , *d_c;
a = (int *)malloc(SIZE * sizeof(int));
b = (int *)malloc(SIZE * sizeof(int));
c = (int *)malloc(SIZE * sizeof(int));
cudaMalloc( &d_a , SIZE * sizeof(int) );
cudaMalloc( &d_b , SIZE * sizeof(int) );
cudaMalloc( &d_c , SIZE * sizeof(int) );
for ( int i = 0 ; i < SIZE ; ++i)
{
a[i] = i ;
b[i] = i ;
c[i] = 0 ;
}
cudaMemcpy(d_a, a, SIZE *sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_b, b, SIZE *sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_c, c, SIZE *sizeof(int), cudaMemcpyHostToDevice);
VectorAdd<<< 1, SIZE >>>(d_a, d_b, d_c, SIZE);
cudaMemcpy(c, d_c, SIZE * sizeof(int), cudaMemcpyDeviceToHost);
for(int i = 0 ; i < 10 ; ++i)
{
printf("C[%d] = %d\n", i, c[i]);
}
free(a);
free(b);
free(c);
cudaFree(d_a);
cudaFree(d_b);
cudaFree(d_c);
return 0;
}
控制台上的輸出為: c[0] = 0 , c[1] = 0 , c[2] = 0 , c[3] = 0 , c[4] = 0 ....
為什么它應該是: c[0] = 0 ; c[1] = 2 ; c[2] = 4 ....
c[0] = 0 ; c[1] = 2 ; c[2] = 4 ....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.