What's the actual use of the Atomics object in ECMAScript?

后端 未结 5 1109
Happy的楠姐
Happy的楠姐 2021-02-07 23:04

The ECMAScript specification defines the Atomics object in the section 24.4.

Among all the global objects this is the more obscure for

5条回答
  •  心在旅途
    2021-02-07 23:28

    Atomics are for synchronising WebWorkers that share memory. They cause memory access into a SharedArrayBuffer to be done in a thread safe way. Shared memory makes multithreading much more useful because:

    • It's not necessary to copy data to pass it to threads
    • Threads can communicate without using the event loop
    • Threads can communicate much faster

    Example:

    var arr = new SharedArrayBuffer(1024);
    
    // send a reference to the memory to any number of webworkers
    workers.forEach(worker => worker.postMessage(arr));
    
    // Normally, simultaneous access to the memory from multiple threads 
    // (where at least one access is a write)
    // is not safe, but the Atomics methods are thread-safe.
    // This adds 2 to element 0 of arr.
    Atomics.add(arr, 0, 2)
    

    SharedArrayBuffer was enabled previously on major browsers, but after the Spectre incident it was disabled because shared memory allows implementation of nanosecond-precision timers, which allow exploitation of spectre.

    In order to make it safe, browsers need to run pages a separate process for each domain. Chrome started doing this in version 67 and shared memory was re-enabled in version 68.

提交回复
热议问题