原子学。JavaScript中的xor()

什么是原子学?

null
  • 原子是JavaScript中的一个对象,它提供了作为静态方法执行原子操作的能力。
  • 就像JavaScript中的Math对象一样,原子的所有属性和方法也是静态的。
  • 原子与SharedArrayBuffer(通用固定长度二进制数据缓冲区)对象一起使用。
  • 原子不像其他全局对象那样是构造器。
  • 原子不能与新操作符一起使用,也不能作为函数调用。

JavaScript中的原子操作 当存在共享内存时,多个线程可以在内存中读写相同的数据。为了确保准确地写入和读取预测值,在当前操作完成之前,另一个操作无法启动。原子操作也不能被中断。

原子学。xor()方法

  • 在原子操作中,有一个内置的原子操作。JavaScript中的xor(),用于计算数组中给定位置的给定值的按位异或。
  • 原子学。xor()操作返回该位置的旧值。
  • 整数typedarray、index和值作为参数传递给函数,并返回存储在相应数组中的值。

语法:

Atomics.xor(typedArray, index, value)

使用的参数:

  1. typedarray:它是共享整数类型的数组 Int8Array , UINT8阵列 , Int16Array
  2. 索引:它是在typedArray中计算按位异或的位置。
  3. value:计算按位异或的数字。

返回值: 原子学。xor()返回给定位置的旧值(typedArray[index])。

下面给出了上述功能的示例:

例如:

Input : arr[0] = 7
        Atomics.xor(arr, 0, 2)
Output : 5
Input : arr[0] = 4
        Atomics.xor(arr, 0, 3)
Output : 7

下面提供了上述功能的代码:

代码1:

<script>
// creating a SharedArrayBuffer
var buf = new SharedArrayBuffer(16);
var arr = new Uint8Array(buf);
// Initialising element at zeroth position of array with 7
arr[0] = 7;
// Displaying the SharedArrayBuffer
console.log(Atomics.load(arr, 0));
// Displaying the return value of the Atomics.xor() method
console.log(Atomics.xor(arr, 0, 2));
// Displaying the updated SharedArrayBuffer
console.log(Atomics.load(arr, 0));


输出:

7
5
5

代码2:

<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 SharedArrayBuffer
console.log(Atomics.load(arr, 0));
// Displaying the return value of the Atomics.xor() method
console.log(Atomics.xor(arr, 0, 5));
// Displaying the updated SharedArrayBuffer
console.log(Atomics.load(arr, 0));


输出:

3
6
6

申请: 每当我们想用任何值计算按位异或并返回计算出的值时,我们都使用原子。JavaScript中的xor()操作。

让我们来看一个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] = 15;
// Displaying the return value of the Atomics.xor() method
console.log(Atomics.xor(myarray, 0, 10));
// Displaying the updated SharedArrayBuffer
console.log(Atomics.load(myarray, 0));


输出:

5
5

例外情况:

  • 如果typedArray不是允许的整数类型之一,那么Atomics。xor()操作抛出一个TypeError。
  • 如果typedArray不是共享类型的数组,那么Atomics。xor()操作抛出一个TypeError。
  • 如果索引用作原子论的参数。xor()操作在类型Darray中超出了界限,然后在原子中超出了界限。store()操作抛出一个Range错误。
© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享