【发布时间】:2017-05-03 04:52:40
【问题描述】:
我想将阵列的一部分从主机上的固定内存复制到 CUDA 设备。例如,我分配了大小为 500 的固定内存,我想将元素 100-399 复制到设备上大小为 300 的数组中。
这是我的代码,
int main()
{
const unsigned int N = 500;
const unsigned int bytes = N * sizeof(int);
cudaError_t status = cudaSuccess;
int *h_a;
int *d_a;
status = cudaMallocHost((void**) &h_a, bytes);
if (status != cudaSuccess)
cout << "Error allocating pinned host memory\n";
status = cudaMalloc((void**) &d_a, bytes);
if (status != cudaSuccess)
cout << "Error allocating pinned device memory\n";
for (int i = 0; i < N; i++) {
h_a[i] = i;
}
status = cudaMemcpy(d_a, h_a + 100, bytes - (200 * sizeof(int)), cudaMemcpyHostToDevice);
if (status != cudaSuccess)
cout << "Error copying to device: " << cudaGetErrorString(status) << "\n";
cudaMemcpy(h_a + 100, d_a, bytes - (200 * sizeof(int)), cudaMemcpyDeviceToHost);
if (status != cudaSuccess)
cout << "Error copying to host: " << cudaGetErrorString(status) << "\n";
cudaFree(d_a);
cudaFreeHost(h_a);
return 0;
}
当我运行它时,我收到主机到设备复制的错误,
Error copying to device: invalid argument
只有主机到设备的复制失败。设备到主机的复制工作正常。此外,如果我使用非固定主机内存,相同的代码也可以正常工作。有没有办法使用固定内存来实现这一点?
【问题讨论】:
-
您发布的代码没有任何问题,它为我运行而没有任何运行时错误。
-
是的,确实如此。很抱歉浪费您的时间。可能,我正在运行另一个使用旧代码的可执行文件。