【问题标题】:How to access members of thrust::device_vector<struct> [duplicate]如何访问推力的成员::device_vector<struct> [重复]
【发布时间】:2018-11-25 13:57:54
【问题描述】:

CUDA 在此处找到了一些文档:https://docs.nvidia.com/cuda/thrust/index.html#vectors,它允许在设备内存/代码中使用向量。我正在尝试创建一个结构类型的向量以用于一般处理。下面是示例代码:

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <iostream>

struct Data
{
  double first, second, total;
};

__global__
void add(thrust::device_vector<Data> *d_matrix)
{
  &d_matrix[1].total = &d_matrix[1].first + &d_matrix[1].second;
}

int main()
{
  thrust::host_vector<Data> matrix;
  thrust::device_vector<Data> *d_matrix;
  int size = sizeof(thrust::host_vector<Data>);

  matrix[1].first = 2100;
  matrix[1].second = 100;

  cudaMalloc(&d_matrix, size);

  cudaMemcpy(d_matrix, &matrix, size, cudaMemcpyHostToDevice);

  add<<<1,1>>>(d_matrix);

  cudaMemcpy(&matrix, d_matrix, size, cudaMemcpyDeviceToHost);

  cudaFree(d_matrix);

  std::cout << "The sum is: " << matrix[1].total;

  return 0;
}

我收到以下错误:

gpuAnalysis.cu(13):错误:类“thrust::device_vector>”没有成员“total”

gpuAnalysis.cu(13):错误:类“thrust::device_vector>”没有成员“first”

gpuAnalysis.cu(13): error: class "thrust::device_vector>" has no member "second"

在编译过程中检测到 3 个错误 “/tmp/tmpxft_000013c9_00000000-8_gpuAnalysis.cpp1.ii”。

根据 nvidia 网站上提供的文档,这些向量能够将所有数据类型存储为 std::vector。有没有办法修复这个错误以访问每个向量元素的结构成员?

【问题讨论】:

  • 这里有很多错误。即使你修复了代码中的分配和运算符优先级问题,它也不起作用,因为你不能在设备代码中使用推力设备向量,
  • 我有什么办法可以在设备代码中使用向量吗?我假设来自 Nvidia 的文档是说推力设备向量允许在设备代码中使用向量。
  • 文档中没有任何地方说明或暗示这一点。您可以在设备代码中访问支持设备向量的内存,但不能使用类本身。
  • 好的。我是 CUDA 的新手,而不是最有经验的程序员。你介意提供一个例子来回答吗?
  • 谢谢我的朋友。副本是我一直在寻找的。我搜索了一段时间,但找不到对我的问题的参考。

标签: c++ vector cuda thrust


【解决方案1】:
void add(thrust::device_vector<Data> *d_matrix) {
   &d_matrix[1].total = &d_matrix[1].first + &d_matrix[1].second;
}

在这段代码中,d_matrix 参数实际上是一个指针,指向thrust::device_vector&lt;Data&gt; 类型的对象。表达式&amp;d_matrix[1].total 是由于计算了 C++ 运算符优先级,因此 d_matrix[1] 被认为是某些不存在的 thrust::device_vector&lt;Data&gt; 类型元素数组的第二个元素,因为指针可以自动被视为数组。这个(不存在的)第二个元素是 .total 成员访问的主题,它不存在。

改用(*d_matrix)[1].total = ...


我也不确定您的代码是否正确。例如,您既没有指定host_vector 也没有指定device_vector 的大小(元素的数量,而不是对象的大小)。你自己也cudaMemcpy矢量对象;它是否也复制了他们的内容?甚至允许吗?我没有使用 Thrust 的经验,但是根据 this page,有更简单的方法来创建 device_vector

【讨论】:

  • 我试过了,但错误仍然存​​在。我只是不确定如何使用 CUDA 访问设备代码中的向量内存。
  • 即使这一切都完成了(而且都完全正确),原始代码中的整个想法是完全错误的,永远无法实现。
猜你喜欢
  • 2013-01-04
  • 1970-01-01
  • 2012-03-08
  • 2019-03-18
  • 2015-05-11
  • 2012-03-18
  • 2013-06-08
  • 2016-10-29
相关资源
最近更新 更多