Atomics.or() คืออะไร
ฟังก์ชัน Atomics.or() ดำเนินการ Bitwise OR แบบอะตอมิก บนค่าที่อยู่ในตำแหน่งที่กำหนดของ typed array ที่แบ่งปัน ฟังก์ชันนี้รับ typed array, ตำแหน่ง (index), และค่า (value) แล้วทำการ OR ระหว่างค่าปัจจุบันกับค่าที่กำหนด เก็บผลลัพธ์ไว้ และคืนค่า เดิม (old value) ก่อนการดำเนินการ
ไวยากรณ์ (Syntax)
Atomics.or(typedArray, index, value)
typedArray- Typed array ที่แบ่งปัน (Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array)index- ตำแหน่งในอาร์เรย์value- ค่าที่จะทำ Bitwise OR
คืนค่า: ค่าที่อยู่ในตำแหน่ง index ก่อน การดำเนินการ OR
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: การทำ OR พื้นฐาน
const buffer = new SharedArrayBuffer(16);
const data = new Uint8Array(buffer);
data[0] = 20; // 00010100 ใน binary
const oldValue = Atomics.or(data, 0, 30); // 30 = 00011110
console.log('ค่าเดิม:', oldValue); // 20
console.log('ค่าใหม่:', Atomics.load(data, 0)); // 30 (00011110)
คำอธิบาย: 20 (00010100) OR 30 (00011110) = 30 (00011110)
ตัวอย่างที่ 2: การตั้งค่า bit เฉพาะ
const buffer = new SharedArrayBuffer(16);
const data = new Uint8Array(buffer);
data[0] = 2; // 00000010
console.log('ก่อน OR:', Atomics.or(data, 0, 7)); // 7 = 00000111, คืนค่า 2
console.log('หลัง OR:', Atomics.load(data, 0)); // 7 (00000111)
คำอธิบาย: ใช้เพื่อ "เปิด" (set) bit ที่ต้องการ โดยค่า 7 (00000111) จะเปิด bit 0, 1, 2
การประยุกต์ใช้ Bitwise OR แบบอะตอมิก
1. Flag Management (การจัดการแฟล็ก)
const FLAGS = {
READ: 1, // 0001
WRITE: 2, // 0010
EXECUTE: 4, // 0100
ADMIN: 8 // 1000
};
const buffer = new SharedArrayBuffer(4);
const permissions = new Uint8Array(buffer);
// เธรด A: ให้สิทธิ์ READ และ WRITE
Atomics.or(permissions, 0, FLAGS.READ | FLAGS.WRITE);
// เธรด B: ให้สิทธิ์ EXECUTE (ไม่ส่งผลต่อ READ, WRITE ที่มีอยู่)
Atomics.or(permissions, 0, FLAGS.EXECUTE);
2. Feature Flags / Feature Toggles
const FEATURES = {
DARK_MODE: 1,
NEW_UI: 2,
BETA_FEATURES: 4,
DEBUG_MODE: 8
};
const buffer = new SharedArrayBuffer(4);
const features = new Uint8Array(buffer);
// เปิดฟีเจอร์ใหม่ๆ โดยไม่กระทบฟีเจอร์เก่า
Atomics.or(features, 0, FEATURES.NEW_UI | FEATURES.BETA_FEATURES);
กรณีพิเศษและข้อผิดพลาด
- โยน
RangeErrorหากindexอยู่นอกขอบเขต - โยน
TypeErrorหากtypedArrayไม่ใช่ integer typed array - ไม่รองรับ
Float32Array,Float64Array,BigInt64Array,BigUint64Array