Search code examples
cudagpgputhrust

How to initialise CUDA Thrust vector without implicitly invoking 'copy'?


I have a pointer int *h_a which references a large number N of data points (on host) that I want to copy to device. So I do:

thrust::host_vector<int> ht_a(h_a, h_a + N);
thrust::device_vector<int> dt_a = ht_a;

However, creating ht_a seems to implictly copy h_a rather than reference it, which is inefficient as I don't need another copy of h_a.

I just want to create ht_a such that &ht_a[0] points to h_a[0] - how to do this?

Many thanks.

Alternatively, as I'm not actually doing anything with ht_a other than copying to device memory, I'd be interested to know if we can go directly between int* and thrust::device_vector<int>.


Solution

  • Edited code to also show how to copy back from device to host:

    #include <stdio.h>
    #include <thrust/device_vector.h>
    #include <thrust/copy.h>
    
    int main() {
    
     int N = 10;
     int *h_a;
     int *h_b;
     h_a = (int *)malloc(N*sizeof(int));
     h_b = (int *)malloc(N*sizeof(int));
     for (int i=0; i<N; i++) {
       h_a[i] = i;
       h_b[i] = 0;
       }
    
     thrust::device_vector<int> dt_a(h_a, h_a + N);
    
     thrust::copy(dt_a.begin(), dt_a.end(), h_b);
    
     for (int i=0; i<N; i++)
       printf("h_b[%d] = %d\n", i, h_b[i]);
     return 0;
    }