Question

I do not know why the below code is not outputting 1,2 but some random numbers

#include <thrust/set_operations.h> 
#include <thrust/device_vector.h> 
#include <ostream> 

int main() { 

    int a[]= { 1,2,3,4,5,6};
    int b[] = {1,2,8};
    int *ga, *gb,*gr;
    cudaMalloc((void**)&ga, 6* sizeof(int));
    cudaMalloc((void**)&gb, 3* sizeof(int));
    cudaMalloc((void**)&gr, 3* sizeof(int));
    cudaMemcpy(ga, a, 6 * sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(gb, b, 3 * sizeof(int), cudaMemcpyHostToDevice);
    thrust::device_ptr<int> end;
    thrust::device_ptr<int> gaptr(ga);
    thrust::device_ptr<int> gbptr(gb);
    thrust::device_ptr<int> grptr(gr);
    end = thrust::set_intersection(gaptr, gaptr+6, gbptr, gbptr+3,grptr);

    printf("%d ", *grptr);
    grptr++;
    printf("%d ", *grptr);  

getchar();

    return 0;


}

Moreover , how to use begin and end1 to iterate over all the values in the result array

Was it helpful?

Solution

You are trying to iterate over an array of ints with an iterator to a device_vector. That is not possible. A pointer is like an iterator for arrays in the sense that you can advance the pointer with operator ++ and access the value it points to with *. You can use the grptr directly instead of trying to create an iterator.

Just this works:

std::cout << *grptr << " ";
grptr++;
std::cout << *grptr << std::endl;

Other notes, don't use printf if you are including . Be consistent and use cout. Also if you really want to try thrust you could be doing that using actual thrust vectors instead of creating arrays, copying them manually and wrapping them in device pointers (unless you are trying to learn inter operation between thrust and the cuda runtime api).

edit: I tried your edited code and indeed printf does not work while cout works. The thing is, thrust::device_ptr is a class which has the unary operator* overloaded and its return type is a thrust::device_reference.

From the documentation:

template<typename T> __host__ __device__ reference thrust::device_ptr<T>::operator*(void) const

This method dereferences this device_ptr.

Returns: a device_reference referring to the object pointed to by this device_ptr.

To have it correctly print the desired value you can just cast it to int:

printf("%d ", (int)*grptr);
grptr++;
printf("%d ", (int)*grptr);

In the initial description of the class thrust::device_reference they give an example with printf stating the solution is a cast. You can check it here http://wiki.thrust.googlecode.com/hg/html/classthrust_1_1device__reference.html

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