Skip to content

Worker Pool

createWorkerPool() (vue-worker-kit/pool) — for many small, independent tasks (resizing hundreds of images, etc.).

ts
import { createWorkerPool } from 'vue-worker-kit/pool'

const pool = createWorkerPool<typeof import('./resize.worker')>(
  () => new Worker(new URL('./resize.worker.ts', import.meta.url), { type: 'module' }),
)

// Pre-create all workers up to size (optional, avoids cold-start latency on first tasks)
await pool.warmup()

// Process array with per-item transfer and global cancellation signal
const thumbnails = await pool.map(files, {
  concurrency: 4,
  transfer: (file) => [file.buffer], // zero-copy per item
  signal: abortController.signal, // cancel all running tasks
})

const one = await pool.run(files[0])

Workers are created lazily, up to size, as tasks arrive — not all at once. size (option) defaults to navigator.hardwareConcurrency — the browser's own count of logical cores/threads on the machine actually running your app, not a number picked at development time. Pass size explicitly to override it (e.g. to cap it, or if navigator reports something you don't want to trust — some privacy-hardened browsers cap or round it). Falls back to 4 where navigator doesn't exist (SSR).

Methods

pool.run(input, options?)

(input: In, options?: { transfer?: Transferable[]; signal?: AbortSignal }) => Promise<Out>

Queues the task on the first free worker.

pool.map(items, options?)

(items: In[], options?: MapOptions) => Promise<Out[]>

Processes an array with bounded parallelism, results in input order.

  • concurrency?: number — max parallel tasks (default: pool.size)
  • transfer?: (item: T) => Transferable[] — per-item zero-copy transfer function
  • signal?: AbortSignal — global cancellation signal for all items

pool.stats

ComputedRef<{ busy: number; idle: number; queued: number }>

Reactive, used by the devtools panel.

pool.terminate()

() => void

Kills the whole pool.

pool.warmup()

() => Promise<void>

Pre-creates all workers up to size without executing tasks.

useWorkerPool()

The same API as createWorkerPool(), with onScopeDispose auto-termination for use directly in setup() — reach for this one instead of createWorkerPool() whenever the pool's lifetime should match the component's.