Search code examples
cudathrust

fail to create and modify device_vector directly


I am starting to use thrust. I just write a simple function to fill the vector, here I have

template <class T> void fillzeros(T &v, int size)
{
  v.reserve(size);
  thrust::fill(v.begin(), v.end(), 0);
}

void main(void)
{
  thrust::device_vector<float> V;
  thrust::host_vector<float> W;

  fillzeros(V, 100); // works
  fillzeros(W, 100); // it doesn't compile, lots of error comes out

  // if I want to crease W, I have to do
  W = V; // so I must generate device vector in advance?

  // I also try the following example shown in the thrust website, still don't compile
  thrust::device_vector<int> vv(4);
  thrust::fill(thrust::device, vv.begin(), vv.end(), 137);
}

it seems that I cannot create and assigned device_vector directly. I have to create host_vector first and assign it to device_vector.

BTW, how can I determine the vector type in the function if I pass it as a template?

p.s. too many errors about thrust::system::detail::generic::unintialized_fill_n


Solution

  • reserve has no effect on a vector size. Therefore your code is doing nothing useful, since W and V start out as size zero and end up as size zero. This code works fine for me:

    $ cat t224.cu
    #include <thrust/device_vector.h>
    #include <thrust/host_vector.h>
    #include <thrust/fill.h>
    #include <thrust/copy.h>
    #include <iostream>
    
    template <class T> void fillzeros(T &v, int size)
    {
      v.resize(size);
      thrust::fill(v.begin(), v.end(), 0);
    }
    
    int main(void)
    {
      thrust::device_vector<float> V;
      thrust::host_vector<float> W;
    
      fillzeros(V, 100); 
      fillzeros(W, 100); 
      std::cout<< "V:" << std::endl;
      thrust::copy(V.begin(), V.end(), std::ostream_iterator<float>( std::cout, " "));
      std::cout<< std::endl << "W:" << std::endl;
      thrust::copy(W.begin(), W.end(), std::ostream_iterator<float>( std::cout, " "));
      std::cout<< std::endl;
    
      return 0;
    }
    $ nvcc -arch=sm_20 -o t224 t224.cu
    $ ./t224
    V:
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    W:
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    $