'Compute shader how to update a shared resource with proper locking/unlocking

I'm currently investigating if it's technically feasible to move some calcuations from a CPU implementation to compute shaders. There is a step where I really need to have exclusive write access to more or less random data locations.

i.e. in a compute shader I need to do as follows:

data[i_rnd] += some_value;

But I really need exclusive addition to the row i_rnd here or the method will fail. The i_rnd comes from a topology but you really don't know when or how it's invoked and it can change in runtime. Meaning the topology will remain constant within the compute shader invokation but it can change between each frame.

In reality data is not as simple as I pretend it to be here and it is not just some flat vertex array. But if I can't do this on a simple array it really doesn't matter.

In a not functional but conceptual code I want to do this:

lock_write(data[i_rnd])
data[i_rnd] += some_value;
unlock_write(data[i_rnd])


Solution 1:[1]

If all you want is to increment an element in a Shader Storage Buffer Object by a specific value atomically, then SSBOs also provide atomic operations, like atomic_add. See also https://www.khronos.org/opengl/wiki/Shader_Storage_Buffer_Object#Atomic_operations.

Solution 2:[2]

For OpenGL, You can simply use atomicAdd() operation on floating-point by enable the NVidia extension. More detail on this link: https://www.khronos.org/registry/OpenGL/extensions/NV/NV_shader_atomic_float.txt

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 httpdigest
Solution 2 hongly