Unified Memory是啥参见其他博主文章,主要就是简化代码,不需要各种cudamalloc和cudamemcpy。
cuda_runtime_api.h中的接口:extern host cudart_builtin cudaError_t CUDARTAPI cudaMallocManaged(void **devPtr, size_t size, unsigned int flags __dv(cudaMemAttachGlobal));
一般传前两个参数即可。
传指针时先在C代码中malloc,然后cudaMallocManaged(),再赋值,否则cudaMallocManaged()会将值重置为0,结构体内指针重置为00000000。
如果代码不能正常运行,将中文注释删掉。
简单数据类型指针:
int *a = nullptr;
a = (int*)malloc(sizeof(int));
*a = 222;
printf("%d\n", *a);//打印是222
...调用cuda函数//无法调用,会报错退出
cudaMallocManaged((void**)&a, sizeof(int));
cudaDeviceSynchronize();
printf("%d\n", *a);//打印是0
...调用cuda函数//cuda中打印也是0
*a = 222;
printf("%d\n"