---
id: wiki-2026-0508-web-worker-웹-워커
title: Web Worker (웹 워커)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Web Worker, 웹 워커, Dedicated Worker]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [web-worker, concurrency, browser, javascript]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: JavaScript/TypeScript
  framework: 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
```js
// 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)
```js
const buf = new ArrayBuffer(64 * 1024 * 1024); // 64MB
worker.postMessage({ buf }, [buf]); // ownership transferred — main thread 의 buf 매 detached
```

### Comlink 매 RPC ergonomics
```js
// 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
```js
// 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
```js
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
```js
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
```js
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
- 부모: [[JavaScript]] · [[Browser Concurrency]]
- 변형: [[Service Worker]] · [[Shared Worker]] · [[Worklet]]
- 응용: [[OffscreenCanvas]] · [[WebAssembly]] · [[WebGPU]]
- Adjacent: [[SharedArrayBuffer]] · [[Comlink]] · [[Atomics]]

## 🤖 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 |
