Open In App

Atomics in JavaScript

Atomics: Atomics is a JavaScript object which gives atomic tasks to proceed as static strategies. Much the same as the strategies for Math object, the techniques, and properties of Atomics are additionally static. Atomics are utilized with SharedArrayBuffer objects. The Atomic activities are introduced on an Atomics module. In contrast to other worldwide articles, Atomics isn’t a constructor. Atomics can’t be utilized with another administrator or can be summoned as a capacity.

Atomic Operations: Atomic operations are not continuous. Multiple threads can read and write data in the memory when memory is shared. There is a loss of data if any data has changed Atomic operations ensure the data is written and accurately read by the predicted values. There is no way to change existing information until the current operation is completed and atomic operations will start.



Methods:

Example 1:






<script>
    var buffer = new 
      
    // create a SharedArrayBuffer
    SharedArrayBuffer(50); 
    var a = new Uint8Array(buffer);
      
    // Initialising element at zeroth position of array with 9 
    a[0] = 9;
    console.log(Atomics.load(a, 0)); 
      
    // Displaying the return value of the Atomics.store() method
    console.log(Atomics.store(a, 0, 3)); 
      
    // Displaying the updated SharedArrayBuffer 
    console.log(Atomics.load(a, 0));  
</script>

Output:

933

Example 2:




<script>
    const buffer = new SharedArrayBuffer(2048);
      
    const ta = new Uint8Array(buffer);
      
    ta[0]; // 0
      
    ta[0] = 5; // 5
      
    Atomics.add(ta, 0, 12);   // 5
      
    Atomics.load(ta, 0);      // 17
      
    Atomics.and(ta, 0, 1); // 17
      
    Atomics.load(ta, 0); // 1
      
    Atomics.exchange(ta, 0, 12); // 1
      
    Atomics.load(ta, 0); // 12
      
    Atomics.compareExchange(ta, 0, 5, 12); // 1
      
    Atomics.load(ta, 0); // 1
      
    Atomics.isLockFree(1); // true
      
    Atomics.isLockFree(2); // true
      
    Atomics.or(ta, 0, 1); // 12
      
    Atomics.load(ta, 0);  // 13
      
    Atomics.store(ta, 0, 12); // 12
      
    Atomics.sub(ta, 0, 2); // 12
      
    Atomics.load(ta, 0); // 10
      
    Atomics.xor(ta, 0, 1); // 10
      
    Atomics.load(ta, 0); // 11  
</script>

Output:

5
17
17
1
1
12
1
1
True
True
13
13
12
12
10
10

Article Tags :