【问题标题】:Understanding of CUDA's cudaGetSymbolAddress理解CUDA的cudaGetSymbolAddress
【发布时间】:2020-06-30 17:23:06
【问题描述】:

我是 CUDA 的新手,现在我正在尝试了解 cudaGetSymbolAddress 的工作原理。我在一个非常简单的代码中遇到了意外的分段错误。我要做的是:

  1. 我声明了一个全局设备变量(device_int)
  2. 在 main() 中,我通过在内核中设置其值来确保定义正确
  3. 我在主机内存中创建了一个指针 (host_pointer_to_device_int) 并通过cudaGetSymbolAddress 使其指向device_int
  4. 我再创建一个指针 (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


【解决方案1】:

(已编辑)

感谢@talonmies

我的错误不是误解 cudaGetSymbolAddress 的工作原理,而是使用带有错误参数类型的 cudaMemcpy:我期望 cudaMemcpy 会为我分配内存,所以我将变量转换为错误的类型。

更正后的代码是:

#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);

    int *host_pointer_to_device_int;
    /* Get a pointer to device_int. After this, I won't be able to access it,
     * but I'm going to copy its value with cudaMemcpy */
    cudaGetSymbolAddress((void **)&host_pointer_to_device_int, device_int);
    assert(cudaGetLastError() == cudaSuccess); // The above operation executed successfully

    int host_int;
    // Copy the device_int's value
    cudaMemcpy(&host_int, host_pointer_to_device_int,
            sizeof(int), cudaMemcpyDeviceToHost);
    assert(cudaGetLastError() == cudaSuccess); // The above operation executed successfully

    cout << host_int << endl; // Everything's fine!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2012-05-30
    • 2012-01-13
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多