您的方法 2 应该有效(我认为方法 3 也应该有效)。您可能对如何在这种情况下进行正确的 CUDA 错误检查感到困惑。
由于您有一个运行时 API 调用失败,如果您在内核调用之后执行 cudaGetLastError 之类的操作,它将显示在 cudaPointerGetAttributes() 调用上之前发生的运行时 API 失败.在您的情况下,这不一定是灾难性的。您要做的是清除该错误,因为您知道它已发生并已正确处理。您可以通过额外调用 cudaGetLastError 来做到这一点(对于这种类型的“非粘性”API 错误,即不暗示 CUDA 上下文损坏的 API 错误)。
这是一个完整的例子:
$ cat t642.cu
#include <stdio.h>
#include <stdlib.h>
#define DSIZE 10
#define nTPB 256
#define cudaCheckErrors(msg) \
do { \
cudaError_t __err = cudaGetLastError(); \
if (__err != cudaSuccess) { \
fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \
msg, cudaGetErrorString(__err), \
__FILE__, __LINE__); \
fprintf(stderr, "*** FAILED - ABORTING\n"); \
exit(1); \
} \
} while (0)
__global__ void mykernel(int *data, int n){
int idx = threadIdx.x+blockDim.x*blockIdx.x;
if (idx < n) data[idx] = idx;
}
int my_func(int *data, int n){
cudaPointerAttributes my_attr;
if (cudaPointerGetAttributes(&my_attr, data) == cudaErrorInvalidValue) {
cudaGetLastError(); // clear out the previous API error
cudaHostRegister(data, n*sizeof(int), cudaHostRegisterPortable);
cudaCheckErrors("cudaHostRegister fail");
}
int *d_data;
cudaMalloc(&d_data, n*sizeof(int));
cudaCheckErrors("cudaMalloc fail");
cudaMemset(d_data, 0, n*sizeof(int));
cudaCheckErrors("cudaMemset fail");
mykernel<<<(n+nTPB-1)/nTPB, nTPB>>>(d_data, n);
cudaDeviceSynchronize();
cudaCheckErrors("kernel fail");
cudaMemcpy(data, d_data, n*sizeof(int), cudaMemcpyDeviceToHost);
cudaCheckErrors("cudaMemcpy fail");
int result = 1;
for (int i = 0; i < n; i++) if (data[i] != i) result = 0;
return result;
}
int main(int argc, char *argv[]){
int *h_data;
int mysize = DSIZE*sizeof(int);
int use_pinned = 0;
if (argc > 1) if (atoi(argv[1]) == 1) use_pinned = 1;
if (!use_pinned) h_data = (int *)malloc(mysize);
else {
cudaHostAlloc(&h_data, mysize, cudaHostAllocDefault);
cudaCheckErrors("cudaHostAlloc fail");}
if (!my_func(h_data, DSIZE)) {printf("fail!\n"); return 1;}
printf("success!\n");
return 0;
}
$ nvcc -o t642 t642.cu
$ ./t642
success!
$ ./t642 1
success!
$
在你的情况下,我认为你没有像我在我放置评论的那一行那样正确处理 API 错误:
// clear out the previous API error
如果你省略这一步(你可以尝试注释掉它),那么当你在 case 0 中运行代码时(即在函数调用之前不要使用固定内存),那么你会出现一个“下一个错误检查步骤(在我的情况下是下一个 API 调用,但在你的情况下可能是在内核调用之后)。