当我在cuda中尝试使用此代码时,为什么会看到黑屏?

1 cuda nsight

我在"visual studio 2010"中使用Win8和Nsight,我为我的显卡(9300m Gs)安装了"310.90-notebook-win8-win7-winvista-32bit-international-whql".但是当我尝试下面的代码时,我看到一个黑屏!并出现错误:"显示驱动程序停止响应并已恢复"!我知道问题出在"cudaMemcpy",但我不知道为什么!?

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>

#define N 8
__global__ void kernel(int *a)
{
int x = threadIdx.x + blockIdx.x * blockDim.x;
int step = x;
while(step<N){
    a[step] =  threadIdx.x;
    step += x;
}
}

int main()
{
int a[N],i=N,j=0;
for(;j<N;j++)
    a[j]=i--;

int *dev_a;
cudaMalloc( (void**)&dev_a, N * sizeof(int) );
cudaMemcpy( dev_a, a, N * sizeof(int), cudaMemcpyHostToDevice);

    kernel<<<2,2>>>(dev_a);

cudaError_t cudaStatus = cudaMemcpy(a, dev_a,N-1 * sizeof(int), cudaMemcpyDeviceToHost);
if (cudaStatus != cudaSuccess) {
    fprintf(stderr, "cudaMemcpy failed!");
    //goto Error;
}

for(j=0;j<N;j++)printf("\n%d",a[j]);

int t;
scanf("%d",&t);
}
Run Code Online (Sandbox Code Playgroud)

sga*_*zvi 10

在内核中,带有threadIdx.x= 0和blockIdx.x= 0的线程,即第一个块的第一个线程将无限期地运行,导致内核崩溃.

threadIdx.x= 0和blockIdx.x= 0时,内核代码将变为:

int x = 0;
int step = 0;
while(step<N)
{
    a[step] =  0;
    step += 0; //This will create infinite loop
}
Run Code Online (Sandbox Code Playgroud)

另外(可能是它的错字),代码的以下行中存在逻辑错误:

cudaError_t cudaStatus = cudaMemcpy(a, dev_a,N-1 * sizeof(int), cudaMemcpyDeviceToHost);
Run Code Online (Sandbox Code Playgroud)

考虑C中的运算符优先级,表达式N-1 * sizeof(int)将计算为N-4(如果sizeof(int)为4).