"매 zero-copy shared memory between JS threads". SharedArrayBuffer (SAB) 는 main thread + Web Worker 간 동일 raw bytes 를 공유. postMessage structured clone 의 copy 비용 제거 + Atomics 로 race-free coordination 가능.
매 핵심
매 동작 모델
매 buffer instance 는 multiple threads 에서 동일 backing store 참조.
매 TypedArray view (Int32Array, Float64Array) 로 typed access.
매 Atomics.load/store/add 로 atomic ops.
매 Atomics.wait/notify 로 futex-like blocking sync.
매 vs ArrayBuffer
매 ArrayBuffer: postMessage 시 structured clone (copy) 또는 transfer (ownership move).
매 SharedArrayBuffer: postMessage 시 reference 전달, 양쪽 동시 access.
classRingBuffer{constructor(sab,capacity){this.head=newInt32Array(sab,0,1);this.tail=newInt32Array(sab,4,1);this.data=newInt32Array(sab,8,capacity);this.cap=capacity;}push(v){constt=Atomics.load(this.tail,0);constnext=(t+1)%this.cap;if(next===Atomics.load(this.head,0))returnfalse;// full
this.data[t]=v;Atomics.store(this.tail,0,next);returntrue;}}
WASM threads memory
constmemory=newWebAssembly.Memory({initial:10,maximum:100,shared:true});// memory.buffer is SharedArrayBuffer
매 결정 기준
상황
Approach
Small data, infrequent
postMessage (clone)
Large buffer, hot path
SAB + Atomics
Transfer ownership once
postMessage with transfer list
Multi-threaded WASM
shared:true Memory
기본값: 매 small data postMessage, 매 hot-path large buffer SAB.
언제: 매 large data parallel processing (image/video/ML inference) 의 + 매 worker 간 frequent sync 필요 시.
언제 X: 매 simple task offload (postMessage 충분) 또는 매 COOP/COEP 헤더 설정 불가능한 환경.
❌ 안티패턴
Non-atomic access on shared view: 매 race condition. 매 always Atomics.* 사용.
Spin without wait: 매 CPU burn. 매 Atomics.wait 으로 block.
Missing COOP/COEP: 매 modern browser 에서 SAB 비활성화. 매 cross-origin isolation 필수.