GPU设备函数如何访问主机功能中定义的对象

How can the GPU device function access class objects defined in host functions?

本文关键字:功能 主机 定义 对象 访问 函数 何访问 GPU      更新时间:2023-10-16

我有一个现有的C 程序,我想将其迁移到GPU版本。内核功能需要访问主机函数中定义的类对象。例如,线程中将使用stringstream对象。但是,它无法通过CUDA中的编译。内核函数如何访问主机函数中定义的类对象?

这是一个例子。

#include <cstdio>
#include <sstream>
using namespace std;
__global__ void kernel(stringstream * sstr)
{
    printf("%sn", sstr->str());
}
int main(int argc, char ** argv)
{
    stringstream * sstr;
    cudaMallocManaged(&sstr, sizeof(stringstream));
    *sstr  << "Hello worldn";
    kernel<<<32, 32>>>(sstr);
    cudaDeviceSynchronize();
    cudaFree(sstr);
    return 0;
}

我有以下编译错误。

$ nvcc -o bin src.cu
src.cu(8): warning: non-POD class type passed through ellipsis
src.cu(8): error: calling a __host__ function("std::__cxx11::basic_stringstream<char,  ::std::char_traits<char> , std::allocator<char> > ::str const") from a __global__ function("kernel") is not allowed
src.cu(8): error: identifier "std::__cxx11::basic_stringstream<char,  ::std::char_traits<char> , std::allocator<char> > ::str const" is undefined in device code
src.cu(8): error: calling a __host__ function("std::__cxx11::basic_string<char,  ::std::char_traits<char> , std::allocator<char> > ::~basic_string") from a __global__ function("kernel") is not allowed
src.cu(8): error: identifier "std::__cxx11::basic_string<char,  ::std::char_traits<char> , std::allocator<char> > ::~basic_string" is undefined in device code
4 errors detected in the compilation of "/tmp/tmpxft_00003bd0_00000000-8_src.cpp1.ii".

您不应在内核内使用C STD类,因为std :: stringstream相关功能已预先编译并从OS链接,NVCC不会生成相应的__device__功能。p>请参阅此主题

std::stringstream可能具有动态分配的数组,您将无法在设备代码中访问。这已经使将这些课程传递给GPU是个坏主意。

您的汇编失败了,因为您还尝试从设备代码调用__host__函数,这是不可能的。如果您想起作用,您可能需要将自定义stringstream适用于CUDA。