Uttaran
Uttaran

Reputation: 59

Atomic block in CUDA

I'm trying to do an atomic read and add in CUDA 8

__device__ int counter = 5;
__global__ void prime()
{
    int num = counter;
    atomicAdd(&counter, 1);
    //......<rest of the code>......
}

atomicAdd() takes care of the add operation. But all my threads read the same value before increment. I want a thread to read, increment then another thread to do the same. Is it possible? Thanks

Upvotes: 1

Views: 698

Answers (1)

talonmies
talonmies

Reputation: 72349

As you can see here, atomicAdd can return the previous value of the variable being atomically updated. So as pointed out in comments, your kernel could be re-written as

__device__ int counter = 5;
__global__ void prime()
{
    int num = atomicAdd(&counter, 1);
    //......<rest of the code>......
}

meaning that num will be assigned the existing value of counter before the atomicAdd operation is performed.

Upvotes: 1

Related Questions