Atomics
The Atomics is an object in JavaScript which provides atomic operations to be performed as static methods. Just like the methods of Math object, the methods and properties of Atomics are also static. Atomics are used with SharedArrayBuffer objects.
The Atromic operations are installed on an Atomics Module. Unlike other global objects, Atomics is not a constructor. Atomics cannot be used with a new operator or can be invoked as a function.
Atomic operations
Atomic operations are not uninterruptible. When memory is shared, multiple threads can read or write an existed data in the memory. So if any data got changed, there will be a loss of data Atomic operations make sure that predicted values(data) are written and read accurately. Atomic operations wont start until and unless the current operation is finished, so there is no way to change an existed data.
Now, lets discuss one of the Automics methods.
Atomics.add()
Atomics.Add() is used to add a given value at a given position in an array and return the old value at that position. Since no interruptions are allowed, no other write function can takes place until the modified value is returned.
Syntax
Atomics.add(typedArray, index, value)
Parameters
typedArray
It's an shared array integer that we are going to modify.
Index
The index in the array where we are going to add a new value.
value
It is nothing but the number we are going to add.
Returned value
Atomics.add() returns the old value at the given position(typedArray[index]).
Example
<html> <body> <script type="text/javascript"> // creating a SharedArrayBuffer var buffer = new SharedArrayBuffer(25); var arr = new Uint8Array(buffer); // Initialising element at zeroth position of array with 6 arr[0] = 6; // Displaying the return value of the Atomics.add() method document.write(Atomics.add(arr, 0, 2)); document.write("</br>"); // Displaying the updated SharedArrayBuffer document.write(Atomics.load(arr, 0)); </script> </body> </html>
Output
6 8