workgroupBarrier
In a compute shader, synchronizes the execution of all threads within the same workgroup. It forces all threads to pause until the last thread in the workgroup reaches this point, preventing race conditions caused by unsynchronized execution, especially when using shared memory (`workgroupArray`).
Core Advantages
By setting a synchronization point between key algorithmic stages, it guarantees the safety and correctness of multi-stage collaborations using workgroup shared memory (`workgroupArray`), such as parallel reductions and tiled computations, serving as a cornerstone for complex parallel algorithms.
Common Uses
Parallel reduction algorithms (e.g., sum, max/min)
Image convolution/filtering (e.g., Gaussian blur)
Tiled matrix multiplication
How to adjust
This node has no tunable parameters; its effect is entirely determined by its 'placement' in the code. It must be inserted between computation stages with data dependencies, especially those relying on shared memory, to ensure correctness. Removing it incorrectly leads to completely wrong results, while adding it unnecessarily severely harms performance.
Code Examples
1// Stage 1: Load data into shared memory
2sharedMemory.element( localId ).assign( dataBuffer.element( ... ) );
3
4// *** Key Point 1: Synchronization Point ***
5// Wait for all threads in the workgroup to finish loading.
6workgroupBarrier();
7
8// Stage 2: Reduction loop
9for ( let stride = WORKGROUP_SIZE / 2; stride > 0; stride /= 2 ) {
10
11 // ... perform reduction on shared memory ...
12
13 // *** Key Point 2: Synchronization Point ***
14 // Wait for the current level of additions to complete.
15 workgroupBarrier();
16
17}