Files
2nd/10_Wiki/Topics/Frontend/Web Worker (웹 워커).md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

5.7 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-web-worker-웹-워커 Web Worker (웹 워커) 10_Wiki/Topics verified self
Web Worker
웹 워커
Dedicated Worker
none A 0.9 applied
web-worker
concurrency
browser
javascript
2026-05-10 pending
language framework
JavaScript/TypeScript Web Platform

Web Worker (웹 워커)

매 한 줄

"매 main thread off-load — UI freeze 의 X". Web Worker 매 separate OS thread 의 JS 실행 — postMessage 의 message-passing, structuredClone 의 transfer. 2026 modern stack 매 OffscreenCanvas + SharedArrayBuffer + Comlink 의 ergonomic wrapper.

매 핵심

매 Worker 종류

  • Dedicated Worker: 1:1 owner — single page 의 사용.
  • Shared Worker: N:1 — 같은 origin 의 multiple tabs share.
  • Service Worker: network proxy — offline / push.
  • Worklet: paint / audio / animation — 매 lightweight, low-latency.

매 message passing

  • postMessage(data, [transfer]) — structuredClone (deep copy).
  • Transferable: ArrayBuffer / MessagePort / OffscreenCanvas — zero-copy ownership transfer.
  • SharedArrayBuffer: 매 진짜 shared memory — Atomics 의 sync (COOP+COEP header 필수).

매 응용

  1. Heavy compute: physics sim / image processing / crypto.
  2. OffscreenCanvas: WebGL/WebGPU rendering on worker — 매 main thread freeze 의 X.
  3. Parsing: large JSON / CSV / protobuf decode.
  4. WASM compute: WebAssembly module 의 worker 의 실행 — 매 isolation.

💻 패턴

Dedicated Worker 매 basic

// main.js
const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
worker.postMessage({ cmd: 'compute', n: 1_000_000 });
worker.onmessage = (e) => console.log('result:', e.data);

// worker.js
self.onmessage = (e) => {
  const { cmd, n } = e.data;
  if (cmd === 'compute') {
    let sum = 0;
    for (let i = 0; i < n; i++) sum += Math.sqrt(i);
    self.postMessage(sum);
  }
};

Transferable ArrayBuffer (zero-copy)

const buf = new ArrayBuffer(64 * 1024 * 1024); // 64MB
worker.postMessage({ buf }, [buf]); // ownership transferred — main thread 의 buf 매 detached
// worker.js
import * as Comlink from 'comlink';
class Engine {
  async heavy(x) { /* ... */ return x * 2; }
}
Comlink.expose(new Engine());

// main.js
import * as Comlink from 'comlink';
const Engine = Comlink.wrap(new Worker('./worker.js', { type: 'module' }));
const engine = await new Engine();
const result = await engine.heavy(42); // 매 promise-based RPC

OffscreenCanvas 매 worker rendering

// main.js
const canvas = document.querySelector('canvas');
const offscreen = canvas.transferControlToOffscreen();
worker.postMessage({ canvas: offscreen }, [offscreen]);

// worker.js
self.onmessage = (e) => {
  const ctx = e.data.canvas.getContext('webgl2');
  // 매 worker thread 의 render loop — 매 main thread 의 jank 의 X
  function frame() { /* draw */ requestAnimationFrame(frame); }
  frame();
};

SharedArrayBuffer + Atomics

const sab = new SharedArrayBuffer(1024);
const view = new Int32Array(sab);
worker.postMessage({ sab });

// worker — 매 atomic increment
Atomics.add(view, 0, 1);
Atomics.notify(view, 0); // wake waiters

// main — 매 wait
Atomics.wait(view, 0, 0); // block until value != 0

Worker pool 매 parallel map

class Pool {
  constructor(size, url) {
    this.workers = Array.from({ length: size }, () => new Worker(url, { type: 'module' }));
    this.queue = [];
    this.idle = [...this.workers];
  }
  exec(task) {
    return new Promise((resolve) => {
      const run = (w) => {
        w.onmessage = (e) => { resolve(e.data); this.idle.push(w); this.flush(); };
        w.postMessage(task);
      };
      this.idle.length ? run(this.idle.pop()) : this.queue.push(run);
    });
  }
  flush() { while (this.queue.length && this.idle.length) this.queue.shift()(this.idle.pop()); }
}

Module worker + dynamic import

const w = new Worker(new URL('./w.js', import.meta.url), { type: 'module' });
// w.js — 매 ESM import 의 가능
import { decode } from './codec.js';
self.onmessage = async (e) => self.postMessage(decode(e.data));

매 결정 기준

상황 Approach
Heavy CPU compute Dedicated Worker + Transferable
GPU render off-main OffscreenCanvas worker
Multi-tab shared state Shared Worker / BroadcastChannel
Offline / cache Service Worker
High-freq sync SharedArrayBuffer + Atomics
Ergonomic RPC Comlink

기본값: Dedicated Worker + Comlink + Transferable buffers.

🔗 Graph

🤖 LLM 활용

언제: main-thread blocking >16ms 의 task / GPU rendering off-main / parallel CPU work. 언제 X: trivial computation (<1ms) — 매 postMessage overhead 의 net loss / DOM access 필요 (worker 의 DOM X).

안티패턴

  • Sync XHR in main: 매 worker 의 reason — main thread 의 block 의 X.
  • Large object clone: structuredClone 매 deep copy — Transferable 의 사용.
  • Worker per task: spawn cost ~5-50ms — pool 의 reuse.
  • No COOP/COEP: SharedArrayBuffer 매 cross-origin isolation 필수.

🧪 검증 / 중복

  • Verified (HTML Living Standard / MDN Web Workers API).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — Worker types, Transferable, OffscreenCanvas, Comlink, SAB patterns