While your GPU threads are able to read from the same location without any problem - as soon as you try and have them write to the same location - you're going to hit a wall of pain! This situation is known as race conditions.
Memory has to be shared - so you have to manage access - especially during 'writing'. Imagine memory as a door - and people as threads - without any coordination or rules - if they all have to write to memory it's like them all trying to get through the door at the same time.
Race conditions occur when multiple threads (or processes access) and manipulate shared data concurrently, and the final outcome depends on the timing and sequence of these accesses. Lead to unpredictable behavior and bugs, as the operations interfere with each other, often resulting in inconsistent or incorrect data.
Their are 2 solutions to this problem:
1. Modify the algorithm so it does not need to write to the same location (e.g., double buffer)
2. Using thread 'atomics' (managing/locking memory blocks)
Each has pros and cons - the extra memory and double buffering approach might require substantially more memory and require multiple iterations to synchronize calculations.
Then again, thread atomics cause 'stalls' (or queues) while threads fight to get access to memory data.
Thread atomics are operations that are performed atomically, ensuring that a thread can complete a read-modify-write sequence on shared data without interruption, preventing race conditions.
Example - With and Without Atomics
The follhowing example has multiple threads each try and add a number to the same memory location. One case will not use an atomic and the other will. As you'll see the non-atomic version produces the incorrect result.
Interestingly as well, you won't get any warnings or errors if you don't use atomics - you'll just get an incorrect answer at the end. For more complex algorithms you might get a situation where it works occasionaly (stability problems). Which is a really really bad things!
Code - Atomic Addition
Start by adding a 'div' element to the window - this will be so we can put any log information on the screen in a big font (size 20). We then add our own 'log' function - which 'appends' the information to the div contents.
let div = document.createElement('div'); document.body.appendChild( div ); div.style['font-size'] = '20pt'; function log( s ) { console.log( s ); let args = [...arguments].join(' '); div.innerHTML += args + '<br>'; }
Just to test the log function works - start by sending the message 'WebGPU Compute Example'
Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.