This simple program showcases the usage of the thrust::device_ptr template.
- A
thrust::device_ptr<int>is instantiated, and memory for ten elements is allocated. - Two more
thrust::device_ptr<int>are instantiated and set to the start- and end-point of the allocated memory region. - Normal pointer arithmetic is used on the
thrust::device_ptr<int>s to calculate the number of elements allocated in step 1. - The elements pointed to by
thrust::device_ptr<int>are initialized usingthrust::sequence. The values of the elements are printed to the standard output. - The first three elements are modified directly in host-code with
thrust::device_ptr::operator[]and all elements are printed to the standard output. - The raw pointer to the device memory is obtained by calling
thrust::device_pointer_cast - The raw pointer is wrapped back to a
thrust::device_ptr<int>. It is asserted that the original and the wrappedthrust::device_ptr<int>are equal. - The sum of the wrapped pointer is calculated with
thrust::reduceand printed to the standard output. - The device memory is freed using
thrust::device_free.
- Thrust's
device_ptris a simple and transparent way of handling device memory the same way one would handle host memory with normal pointers. - Unlike a normal pointer to device memory
device_ptradds type safety, and the underlying device memory is transparently accessible on the host. - The
device_ptrcan be used in Thrust algorithms like a normal pointer to device memory. - The "raw" normal pointer to the device memory for usage in kernels or other APIs can be obtained from a
device_ptrby usingthrust::raw_pointer_cast. device_ptris not a smart pointer. Allocating and freeing memory lies in the responsibility of the programmer.
thrust::device_ptr<T>::operator=thrust::device_ptr<T>::operator[]thrust::device_malloc<T>thrust::sequencethrust::raw_pointer_castthrust::device_pointer_castthrust::reducethrust::device_free