c++ - 对 STL 拷贝的推力无法按预期工作

标签 c++ vector stl cuda thrust

我不确定 thrust::copy 到 STL vector 的实际工作方式。 当我执行以下操作时,它会给我预期的结果:

struct TestOperation
{
    TestOperation(){}

    __host__ __device__
   CustomPoint operator()(const CustomPoint& point)
   {
       CustomPoint pt;
       pt.x = point.x * 2;
       pt.y = point.y * 2;
       pt.z = point.z;
       return pt;
   }
};
void CudaLoader::TestLoader(std::vector<CustomPoint>& customPoints) //Host vector reference
    {
       thrust::device_vector<CustomPoint> devicePoints(customPoints.begin(), customPoints.end());
       thrust::device_vector<CustomPoint> output;
       output.reserve(devicePoints.size());
       thrust::transform(devicePoints.begin(), devicePoints.end(), output.begin(), TestOperation());
       for (int i = 0; i < customPoints.size(); i++)
       {
           customPoints[i] = output[i];
       }
    }

但是遍历所有元素,尤其是当元素很多时,对我来说似乎不是最佳选择,所以我想使用 copy。但是当我尝试这样做时:

thrust::copy(output.begin(), output.end(), customPoints.begin());

而不是循环,然后我没有得到预期的结果 - 作为参数给出的引用的主机 STL vector 保持不变。此外,output.size() 返回 0,但我发现存储大小是正确的。这是为什么?

最佳答案

问题的根源是这样的:

   thrust::device_vector<CustomPoint> output;
   output.reserve(devicePoints.size()); 

reserve 仅更改 vector 的保证最小存储分配。它不会改变其大小。在上面的代码中,output.size() 仍然是 0。还要注意 thrust::transform 不会改变输出 vector 的大小。只要有足够的有效内存来保存转换的输出,执行转换操作的推力闭包内核就不会产生非法内存访问错误。

改为这样做:

   thrust::device_vector<CustomPoint> output;
   output.resize(devicePoints.size());
   thrust::transform(devicePoints.begin(), devicePoints.end(), output.begin(), TestOperation());

然后

thrust::copy(output.begin(), output.end(), customPoints.begin());

将按预期工作,因为 output 具有非零大小。

关于c++ - 对 STL 拷贝的推力无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31239498/

相关文章:

c++ - 如何抛出文件和行号错误?

c++ - Boost Asio 示例 HTTP 服务器——采用此示例并将其设为 "production ready"

R:制作2个子集向量,以便值在索引方面不同

c++ - 使用来自控制台的输入来分割列表的故障初始化 vector

c++ - 从 std::back_insert_iterator 派生?

c++ - 在C++中对while循环进行多线程

c++ - 为什么填充数据成员会出现这种不一致?

c++ - 如果没有找到 map 元素会返回什么?

c++ - STL/Boost 中的仿函数,它从指针中提取值

C++ STL : Why allocators don't increase memory footprint of containers?