cuda编程

dwandqq 2018-01-10 10:18:07
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <malloc.h>
#include <cuda.h>
#include <curand.h>
#include <cuda_runtime.h>
int main()
{
int *h_a,*h_a1,*d_a;
h_a = (int *)malloc(sizeof(int));
h_a1 = (int *)malloc(sizeof(int));
CUDA_CALL(cudaMalloc((void **)&d_a,sizeof(int)));
h_a[0]=5;
cudaMemcpy(d_a, h_a,sizeof(int),cudaMemcpyHostToDevice);
cudaMemcpy(h_a1, d_a,sizeof(int),cudaMemcpyDeviceToHost);
printf("%d\n",h_a1[0]);
return 0;
}
想问一下,为什么输出结果为0,而不是5?求大神解答
...全文
605 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Javen_ManWJ 2019-05-07
  • 打赏
  • 举报
回复
在printf("%d\n",h_a1[0]);前面加入阻塞函数cudaDeviceSynchronize();保证主机端等待设备端完成操作再进行下一步操作。
dwandqq 2018-01-10
  • 打赏
  • 举报
回复
刚才弄错了,是这样 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <malloc.h> #include <cuda.h> #include <curand.h> #include <cuda_runtime.h> int main() { int i; int *h_a,*h_a1,*d_a; h_a = (int *)malloc(sizeof(int)); h_a1 = (int *)malloc(sizeof(int)); CUDA_CALL(cudaMalloc((void **)&d_a,sizeof(int))); h_a[0]=5; for(i=0;i<4;i++) { cudaMemcpy(d_a, h_a,sizeof(int),cudaMemcpyHostToDevice); cudaMemcpy(h_a1, d_a,sizeof(int),cudaMemcpyDeviceToHost); printf("%d\n",h_a1[0]); } return 0; }

2,408

社区成员

发帖
与我相关
我的任务
社区描述
高性能计算
社区管理员
  • 高性能计算社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧