I am unable to get the source of segmentation fault in this short cuda code. I am using it to test the sorting speed of the Thrust library versus the STL library for sorting integers. I am passing the size of the array of doubles to be sorted as a command line argument.
Here is the code
inline void check_cuda_error(char *message)
{
cudaThreadSynchronize();
cudaError_t error = cudaGetLastError();
if(error != cudaSuccess)
{
printf("CUDA error after %s: %s\n", message, cudaGetErrorString(error));
}
}
int main(int argc, char *argv[])
{
int N = atoi(argv[1]);
double* h = new double[N];
for (int i = 0; i < N; ++i)
{
h[i] = (double)rand()/RAND_MAX; //std::cout << h[i] << " " ;
}
clock_t start , stop;
std::cout << std::endl;
// Start timing
start = clock();
std::sort(h, h+N);
stop = clock();
std::cout << "Host sorting took " << (stop - start) /(double)CLOCKS_PER_SEC << std::endl ;
// Start the GPU work. Initialize to random numbers again.
for (int i = 0; i < N; ++i)
{
h[i] = (double)rand()/RAND_MAX; //std::cout << h[i] << " " ;
}
double* d = 0;
const size_t num_bytes = N * sizeof( double );
cudaMalloc((void**)&d, num_bytes);
check_cuda_error("Memory Allocation");
cudaMemcpy(d ,h , N * sizeof(double), cudaMemcpyHostToDevice); // Transfer data
thrust::sort( d, d+ N ) ;
return 0;
}
I get the following errors
[BeamerLatex/Farber]$ nvcc -arch=sm_20 sortcompare.cu ; ./a.out 16777216
Host sorting took 3.77
[1] 4661 segmentation fault ./a.out 16777216
[BeamerLatex/Farber]$
Seems that you cannot run thrust::sort on a raw pointer, you need to cast it to device_ptr
first, ie.:
thrust::device_ptr< double > dv = thrust::device_pointer_cast(d);
thrust::sort( dv, dv+ NN ) ;
this works fine for me.