c++ - 如何访问推力::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。有没有办法解决这个错误来访问每个向量元素的结构成员?
解决方案
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_vector
和device_vector
. 您还cudaMemcpy
矢量对象本身;它是否也复制了他们的内容?甚至允许吗?我没有使用 Thrust 的经验,但是根据这个页面,有更简单的创建方法device_vector
。
推荐阅读
- sql - 如果您的连接字符串不支持身份验证关键字,如何连接到 Azure DB
- c# - 在 C# 中,如何根据对象数组创建数组数组?
- reporting-services - SSRS Table Cell Mailto 链接(无论是“转到 URL”操作还是 HREF 链接)重复并掩盖了表格结果?
- python - 如何使用 python web 驱动程序搜索两个元素
- c# - 如何在用户控件的 xml 标记中指定委托或事件处理程序(不在代码后面)?
- angular - Angular 指令不更新 ngModel
- c - 仅使用单链表对姓名、姓氏、id 字母顺序进行排序
- c# - 如何使用实体框架 6 更新具有唯一列的表上的条目
- linux - 如何使用 bash 单独压缩超过 x 天的文件?(有用户输入)
- wordpress - 如何使用自定义表单标签中的值