什么是原子学?
- 原子是JavaScript中的一个对象,它提供了作为静态方法执行原子操作的能力。
- 就像JavaScript中的Math对象一样,原子的所有属性和方法也是静态的。
- 原子与SharedArrayBuffer(通用固定长度二进制数据缓冲区)对象一起使用。
- 原子不像其他全局对象那样是构造器。
- 原子不能与新操作符一起使用,也不能作为函数调用。
JavaScript中的原子操作 当存在共享内存时,多个线程可以在内存中读写相同的数据。为了确保准确地写入和读取预测值,在当前操作完成之前,另一个操作无法启动。原子操作也不能被中断。 原子学。isLockFree()方法
- 原子学。如果给定的大小是integer TypedArray types else Atomics的BYTES_PER_ELEMENT属性之一,isLockFree()操作将返回true。isLockFree()操作返回false。
- 无锁元素可以在不需要锁的情况下进行操作,用户不需要提供自己的锁机制。
整数类型Darray的字节/元素属性是什么?
- Darray的打字机。BYTES_PER_ELEMENT属性表示类型化数组中每个元素的字节大小。
- 因为TypedArray对象在每个元素的字节数和字节的解释方式上彼此不同。
- BYTES_PER_ELEMENT常量包含给定类型Darray中每个元素的字节数。
应用:
- 原子学。isLockFree()用于检查操作是否无锁。
- 可用于验证integer TypedArray的BYTES_PER_ELEMENT属性。
语法:
Atomics.isLockFree(size)
使用的参数: 大小:它是要检查的字节大小 返回值: 原子学。isLockFree()返回布尔值true,表示操作没有锁,或者返回false。
下面提供了上述功能的示例 .
Input : Atomics.isLockFree(5)Output : false
说明:在本例中,“5”作为参数发送给原子。isLockFree()方法,它返回false,因为“5”不是每个元素的字节值之一。
Input : Atomics.isLockFree(6)Output : false
说明:在本例中,“6”作为参数发送给原子。isLockFree()方法,它返回false,因为“6”不是每个元素的字节值之一。
Input : Atomics.isLockFree(2)Output : true
说明:在本例中,“2”作为参数发送给原子。isLockFree()方法,它返回true,因为“2”是每个元素的字节值之一。
Input : Atomics.isLockFree(4)Output : true
说明:在本例中,“4”作为参数发送给原子。isLockFree()方法,它返回true,因为“4”是每个元素的字节值之一。 下面提供了上述功能的代码。 代码1:
javascript
<script> // Displaying the return value of the // Atomics.isLockFree() method console.log(Atomics.isLockFree(5)); // Atomics.isLockFree() will return false since // 5 is not one of the BYTES_PER_ELEMENT values </script> |
输出:
false
代码2:
javascript
<script> // Displaying the return value of // the Atomics.isLockFree() method console.log(Atomics.isLockFree(6)); // Atomics.isLockFree() will return false since 6 // is not one of the BYTES_PER_ELEMENT values </script> |
输出:
false
代码3:
javascript
<script> // Displaying the return value // of the Atomics.isLockFree() method console.log(Atomics.isLockFree(2)); // Atomics.isLockFree() will return true since // 2 is one of the BYTES_PER_ELEMENT values </script> |
输出:
true
代码4:
javascript
<script> // Displaying the return value of the // Atomics.isLockFree() method console.log(Atomics.isLockFree(4)); // Atomics.isLockFree() will return true since // 4 is one of the BYTES_PER_ELEMENT values </script> |
输出:
true
申请: 无论何时,我们想要检查一个操作是否无锁,或者想要验证integer TypedArray的BYTES_PER_ELEMENT属性,我们都会使用原子。JavaScript中的isLockFree()操作。 让我们来看一个JavaScript程序:
javascript
<script> // Displaying the return value of // the Atomics.isLockFree() method console.log(Atomics.isLockFree(8)); // Atomics.isLockFree() will return true since 8 // is one of the BYTES_PER_ELEMENT(Float64Array) values </script> |
输出:
true
例外情况:
- 如果typedArray不是允许的整数类型之一,那么Atomics。isLockFree()操作抛出一个TypeError。
- 如果typedArray不是共享类型的数组,那么Atomics。isLockFree()操作抛出一个TypeError。
支持的浏览器:
- 谷歌浏览器
- 微软边缘
- 火狐