首页 > 解决方案 > 如何访问推力::device_vector 的成员

问题描述

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):错误:类“thrust::device_vector>”没有成员“second”

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

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

标签: c++vectorcudathrust

解决方案


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<Data>。该表达式&d_matrix[1].total是由于 C++ 运算符优先级计算的,因此它d_matrix[1]被认为是一些不存在的类型元素数组的第二个元素thrust::device_vector<Data>,因为指针可以自动被视为数组。这个(不存在的)第二个元素然后是.total成员访问的主题,它不存在。

试试(*d_matrix)[1].total = ...吧。


另外我不确定您的代码是否正确。例如,您没有指定 yourhost_vectordevice_vector. 您还cudaMemcpy矢量对象本身;它是否也复制了他们的内容?甚至允许吗?我没有使用 Thrust 的经验,但是根据这个页面,有更简单的创建方法device_vector


推荐阅读