atomicSub
Performs a thread-safe atomic subtraction operation on a value in shared memory (usually a Storage Buffer), used to safely consume resources or decrement counters in parallel computations.
Core Advantages
Guarantees the atomicity of the 'read-compute-write' cycle at the hardware level, preventing 'lost subtractions' from race conditions, making it a core tool for implementing parallel resource management (like reference counting and semaphores).
Common Uses
Managing a shared resource pool by decrementing a counter to consume or acquire resources.
Implementing reference counting to safely decrement the reference number when an object releases a resource.
Aggregating damage in destructible environments by subtracting damage from an object's health points.
How to adjust
Its effect is controlled by the `valueNode` (the value to subtract). In the energy shield example, `valueNode` represents the bullet's power. Increasing the damage value from 50 to 150 is like upgrading a 'submachine gun' to an 'anti-tank cannon', causing each hit to deplete the shield's energy much faster and create a more significant visual damage effect.
Code Examples
1// Define the damage value per bullet
2const damage = 50;
3// Atomically subtract the damage from the shield's health at the hit point
4atomicSub(shieldHealthBuffer.element(index), damage);