CUDA Thrust: Is it possible to have two device_vectors point to overlapping memory?

StackOverflow https://stackoverflow.com//questions/12689801

  •  12-12-2019
  •  | 
  •  

Question

If I initialize x using thrust::device_vector<double> x(10), is it possible to create a device_vector y that spans x[2] through x[5]?

Note: I don't want memory to be copied, which happens when I use something like thrust::device_vector<double> y(x.begin(), x.end()).

Was it helpful?

Solution

The thrust device_vector only has allocation or copy constructors, so there isn't a direct way to alias an existing vector or device pointer by constructing another device_vector. But as pointed out in comments, it really isn't needed either. Thrust algorithms always work on iterators, and it is possible to use iterator arithmetic to achieve the same outcome. For example this, creates a new vector via copy construction:

thrust::device_vector<double> x(10);
thrust::device_vector<double> y(x.begin()+2, x.begin()+5);

double val = thrust::reduce(y.begin(), y.end());

whereas this returns the same answer without it:

thrust::device_vector<double> x(10);

double val = thrust::reduce(x.begin()+2, x.begin()+5);

The result is the same in both cases, the second equivalent to creating an alias to a subset of the input vector.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top