对STL副本的推力不能按预期工作

时间:2015-07-06 06:59:35

标签: c++ vector stl cuda thrust

我不确定STL向量的thrust::copy实际上是如何工作的。 当我执行以下操作时,它会给出我预期的结果:

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向量保持不变。此外,output.size()返回0,但我看到存储大小是正确的。这是为什么?

1 个答案:

答案 0 :(得分:4)

问题的根源是:

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

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

请改为:

   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的大小非为零。

相关问题