5

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>.

mchen
  • 9,808
  • 17
  • 72
  • 125

1 Answers1

5

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;
}
Robert Crovella
  • 143,785
  • 11
  • 213
  • 257
  • Thanks, but how to do I get back from `dt_a` to `h_a` (i.e. `thrust::device_vector` to host `int*`)? – mchen Jan 15 '13 at 01:17
  • Thanks. Are these operations synchronous? – mchen Jan 15 '13 at 02:09
  • Yes, all of the thrust copy operations I've shown above are synchronous (both the implicit copy on creation of `dt_a` and the explicit `thrust::copy` without an execution policy). Meaning control is not returned to the host thread until the function is complete – Robert Crovella Jun 11 '15 at 19:45
  • `malloc` in C++ code?? Even in 2013 `new` was the way to go.. (nowadays it would be `std::unique_ptr`.) memory leak btw. – JHBonarius Jun 17 '18 at 08:27