ECMAScript中Atomics对象的实际用途是什么? [英] What's the actual use of the Atomics object in ECMAScript?

查看:227
本文介绍了ECMAScript中Atomics对象的实际用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ECMAScript规范定义< 24.4 部分中的strong> Atomics对象。

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

在所有全局对象中,这对我来说更加模糊,因为我没有直到我没有阅读它的规格才知道它的存在,谷歌也没有多少引用它(或者这个名字太通用了,一切都被淹没了?)。

Among all the global objects this is the more obscure for me since I didn't know about its existence until I didn't read its specification, and also Google hasn't many references to it (or maybe the name is too much generic and everything gets submerged?).

根据其官方定义


Atomics对象提供在共享内存阵列单元上不可分割地(原子地)运行的函数
以及允许代理等待和发送原始事件的函数

The Atomics object provides functions that operate indivisibly (atomically) on shared memory array cells as well as functions that let agents wait for and dispatch primitive events

因此它具有一个具有多个对象的对象的形状处理低级内存并调节对它的访问的方法。它的公共界面也让我想到了。但是这种对象对最终用户的实际使用是什么?为什么公开?是否有一些可用的例子?

So it has the shape of an object with a number of methods to handle low-level memory and regulate the access to it. And also its public interface makes me suppose it. But what's the actual use of such object for the end-user? Why is it public? Are there some examples where it can be useful?

谢谢

推荐答案

Atomics用于同步共享内存的WebWorkers 。它们导致对SharedArrayBuffer的内存访问以线程安全的方式完成。共享内存使多线程更有用,因为:

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:


  • 没有必要复制数据以将其传递给线程

  • 线程可以在不使用事件循环的情况下进行通信

  • 线程可以更快地进行通信

示例:

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 ,但在幽灵事件之后,它被禁用,因为共享内存允许实现纳秒级精度定时器,允许利用幽灵。

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.

为了使其安全,浏览器需要为每个域运行页面一个单独的进程。 Chrome在版本67中开始执行此操作,并在版本68中重新启用了共享内存。

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.

这篇关于ECMAScript中Atomics对象的实际用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆