直入正题。看下面一段程序:
#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>
__global__ void test01_kernel(float *od)
{
char tx = threadIdx.x;
if (od[tx]>0.0f)
{
od[tx]+=1.0f;
}
od[tx]+=1.0f;
}
int main()
{
float *hd, *dd;
int tn = 16;
hd = (float*)malloc(tn*sizeof(float));
cudaMalloc((void**)(&dd), tn*sizeof(float));
//cudaMemset(dd, 0, tn*sizeof(float));
test01_kernel<<<1,tn>>>(dd);
cudaMemcpy(hd, dd, tn*sizeof(float), cudaMemcpyDeviceToHost);
for (int i = 0; i < tn; i++)
{
printf("i = %2d %.2f\n", i, hd[i]);
}
free(hd);
cudaFree(dd);
getchar();
return 0;
}
我把初始化的程序段注释掉了。有兴趣的童鞋可以在Debug模式下多运行几下。
我运行两次的结果:第一结果全部出来的是1.00,第二次运行下成了3.00了。呵呵真有意思,大家可要小心了!