【发布时间】:2020-06-30 17:23:06
【问题描述】:
我是 CUDA 的新手,现在我正在尝试了解 cudaGetSymbolAddress 的工作原理。我在一个非常简单的代码中遇到了意外的分段错误。我要做的是:
- 我声明了一个全局设备变量(
device_int) - 在 main() 中,我通过在内核中设置其值来确保定义正确
- 我在主机内存中创建了一个指针 (
host_pointer_to_device_int) 并通过cudaGetSymbolAddress使其指向device_int - 我再创建一个指针 (
host_pointer_to_host_int) 并尝试cudaMemcpy从 host_pointer_to_device_int 到 host_pointer_to_host_int 的值
所有这些操作都没有错误地完成,但是在尝试打印host_pointer_to_host_int 的值时出现分段错误。代码如下:
#include <iostream>
#include <cassert>
using namespace std;
__device__ int device_int;
__global__ void kernel()
{
device_int = 1000;
}
int main()
{
kernel<<<1, 1>>>();
assert(cudaGetLastError() == cudaSuccess); // The above operation executed successfully
int *host_pointer_to_device_int;
cudaGetSymbolAddress((void **)&host_pointer_to_device_int, device_int);
assert(cudaGetLastError() == cudaSuccess); // The above operation executed successfully
int *host_pointer_to_host_int;
// Copy the device_int's value
cudaMemcpy((void **)&host_pointer_to_host_int, host_pointer_to_device_int,
sizeof(int), cudaMemcpyDeviceToHost);
assert(cudaGetLastError() == cudaSuccess); // The above operation executed successfully
cout << *host_pointer_to_host_int << endl; // Segmentation fault
}
【问题讨论】:
-
host_pointer_to_host_int 没有意义。您试图将值 int(1000) 视为指针,这显然是错误的。 host_pointer_to_host_int 应该只是一个 int,而不是一个指针。您使用设备符号没有任何问题
标签: memory memory-management cuda