再贴一遍代码:
#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; }
在你多次重新运行这段程序时,cudaMalloc分给dd的是同一块内存啊,第一次运行时,他有初始值0.0f,后面运行的时候,他就有值了。所以在原先的值上加一。不行你可以tn=16的时候多运行几次,比如运行三次,然后tn=32,你再看一遍结果!惊呆了,呵呵,前16个为5.00,后16个竟然为1.00!
有意思!!