Counter in Loop not Work Correct

hi

i have a 1D matrix of coordinates (x[N]) and want to for each element of this array search that how many element is in the distance epsilon of that element. so i have a double loop, it’s like this code:

i=blockIdx.x * blockDim.x + threadIdx.x;

if(i < N-1){

for(j = 0; j < N; j++){

delta =  x[i] - x[j];

if (delta < eposilon) counter += 1;

}

}

the problem is counter only for thread i = N-2 increasing and show the value counted for this thread, so it dos not counting the correct value. how can i place a counter in this double loop? please help me!

If ‘counter’ is a variable in global or shared memory then you have to use atomic operations. The way you’re doing it causes write conflicts when more than one thread tries to increment ‘counter’ at the same time.

thanks a lot!