CUDA内核似乎不被称为

时间:2019-10-31 18:39:02

标签: cuda

我可以知道为什么以下简单的cuda程序在带有CC5.2的设备上失败了吗?

#include <iostream>
#include <math.h>
#include <stdlib.h>
#define N 1

__global__ void vector_addition( int *a, int *b, int *c )
{
  int i = blockDim.x + blockIdx.x + threadIdx.x;
  if ( i < N )
    c[ i ] = a[ i ] + b[ i ];
}

int main()
{
  size_t bytes = N*sizeof( int );
  int *A = (int *)malloc(bytes);  
  int *B = (int *)malloc(bytes);  
  int *C = (int *)malloc(bytes);

  int *d_A, *d_B, *d_C;
  cudaMalloc( &d_A, bytes ); 
  cudaMalloc( &d_B, bytes );  
  cudaMalloc( &d_C, bytes );

  for ( int i = 0; i < N; i++ ) {
    A[ i ] = 1; B[ i ] = 2; C[ i ] = 0;
  }

  cudaMemcpy( d_A, A, bytes, cudaMemcpyHostToDevice );
  cudaMemcpy( d_B, B, bytes, cudaMemcpyHostToDevice );

  int thr_per_blk = 1024;
  int blk_in_grid = ceil( float( N ) / thr_per_blk );

  vector_addition<<< blk_in_grid, thr_per_blk >>>( d_A, d_B, d_C );

  cudaMemcpy( C, d_C, bytes, cudaMemcpyDeviceToHost );
  for ( int i = 0; i < N; i++ ) {
    if ( C[ i ] != 3 ) {
      std::cout << "error\n";
    }
  }

  free( A ); free( B ); free( C );
  cudaFree( d_A ); cudaFree( d_B ); cudaFree( d_C );

  return 0;
}

输出为error消息。

1 个答案:

答案 0 :(得分:2)

您的内核中的这一行不正确:

int i = blockDim.x + blockIdx.x + threadIdx.x;

这不是生成一维索引的正确方法。应该是:

int i = blockDim.x * blockIdx.x + threadIdx.x;

如果索引不正确,第一个线程应该为全局唯一索引生成0,它会生成1024 + 0 + 0 =1024。这在内核中的if测试中失败,因此实际上没有线程做任何东西。