通过引用将thrust::device_vector传递给函数

passing thrust::device_vector to a function by reference

本文关键字:vector 函数 device 引用 thrust      更新时间:2023-10-16

我试图通过device_vector的结构

struct point 
{
    unsigned int x;
    unsigned int y;
}

以下列方式传递给函数:

void print(thrust::device_vector<point> &points, unsigned int index)
{
    std::cout << points[index].y << points[index].y << std::endl;
}

myvector已正确初始化

print(myvector, 0);

我得到以下错误:

error: class "thrust::device_reference<point>" has no member "x"
error: class "thrust::device_reference<point>" has no member "y"

怎么了?

不幸的是,device_reference<T>不能暴露T的成员,但它可以转换为T

要实现print,通过将每个元素转换为临时temp来临时复制它:

void print(thrust::device_vector<point> &points, unsigned int index)
{
    point temp = points[index];
    std::cout << temp.y << temp.y << std::endl;
}

每次调用print时,它都会导致从GPU到系统内存的传输以创建临时内存。如果需要一次打印整个points集合,更有效的方法是将整个向量points全部复制到host_vectorstd::vector(使用thrust::copy),然后像往常一样遍历集合。

From http://thrust.googlecode.com/svn/tags/1.1.0/doc/html/structthrust_1_1device__reference.html:

device_reference作为对存储在设备内存中的对象的引用。Device_reference不打算直接使用;相反,这种类型是推迟device_ptr的结果。类似地,获取device_reference的地址会产生device_ptr。

也许你需要一些像

(&points[index]).get()->x
不是

points[index].x

这有点难看,但是CUDA需要一种机制来在RAM和GPU之间传输数据。