什么是原子学?
null
- 原子是JavaScript中的一个对象,它提供了作为静态方法执行原子操作的能力。
- 就像JavaScript中的Math对象一样,原子的所有属性和方法也是静态的。
- 原子与SharedArrayBuffer(通用固定长度二进制数据缓冲区)对象一起使用。
- 原子不像其他全局对象那样是构造器。
- 原子不能与新操作符一起使用,也不能作为函数调用。
JavaScript中的原子操作 当存在共享内存时,多个线程可以在内存中读取和写入相同的数据。为了确保准确地写入和读取预测值,在当前操作完成之前,另一个操作无法启动。原子操作也不能被中断。 原子学。sub()方法 在原子操作中,有一种方法是原子学。sub(),用于减去数组中给定位置的给定值,并返回该位置的旧值。在回写修改后的值之前,不能执行其他写入操作。 语法:
Atomics.sub(typedArray, index, value)
使用的参数:
- 类型Darray: 它是要修改的共享整数类型数组。
- 索引: 它是typedArray中要从中减去值的位置。
- 价值: 这是你想减去的数字。
- 原子学。sub()返回给定位置的旧值(typedArray[index])。
下面提供了上述功能的示例。 例如:
Input : arr[0] = 9; Atomics.sub(arr, 0, 3);Output : 9
Input : arr[0] = 3; Atomics.sub(arr, 0, 2);Output : 3
下面提供了上述功能的代码。 代码1:
javascript
<script> // creating a SharedArrayBuffer var buf = new SharedArrayBuffer(25); var arr = new Uint8Array(buf); // Initialising element at zeroth position of array with 9 arr[0] = 9; // Displaying the return value of the Atomics.sub() method console.log(Atomics.sub(arr, 0, 3)); // Displaying the updated SharedArrayBuffer console.log(Atomics.load(arr, 0)); </script> |
输出:
96
代码2:
javascript
<script> // creating a SharedArrayBuffer var buf = new SharedArrayBuffer(25); var arr = new Uint8Array(buf); // Initialising element at zeroth position of array with 3 arr[0] = 3; // Displaying the return value of the Atomics.sub() method console.log(Atomics.sub(arr, 0, 2)); // Displaying the updated SharedArrayBuffer console.log(Atomics.load(arr, 0)); </script> |
输出:
31
申请: 每当我们想要更新(减去)给定数组中指定位置的值,并想要返回该位置的旧值时,我们就使用原子。JavaScript中的sub()操作。 让我们来看一个JavaScript程序:
javascript
<script> // creating a SharedArrayBuffer var mybuffer = new SharedArrayBuffer(25); var myarray = new Uint8Array(mybuffer); // Initialising the element at zeroth position of array myarray[0] = 40; // Displaying the return value of the Atomics.sub() method console.log(Atomics.sub(myarray, 0, 20)); // Displaying the updated SharedArrayBuffer console.log(Atomics.load(myarray, 0)); </script> |
输出:
4020
例外情况:
- 如果typedArray不是允许的整数类型之一,那么Atomics。sub()操作抛出一个类型错误。
- 如果typedArray不是共享类型的数组,那么Atomics。sub()操作抛出一个类型错误。
- 如果索引用作原子论的参数。sub()操作超出了类型Darray和原子的界限。sub()操作抛出一个Range错误。
支持的浏览器:
- 谷歌浏览器
- 微软边缘
- 火狐
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END