Perfomance & ScalingLesson 88Free preview
Worker Threads
This lesson is part of Node.js · All levels
Summary
This lesson discusses worker_threads, how to run CPU-bound code on separate threads in a single process. Unlike clusters, workers share memory through SharedArrayBuffer and communicate via postMessage. It's the perfect solution for heavy computing like cryptography, compression, or large parsing without blocking the event loop. (Node.js)
Key points
- Make a worker with new Worker(path) or new Worker(code, { eval: true }).
- Two-way communication through postMessage and event 'message'.
- SharedArrayBuffer + Atomics allows you to share buffers between threads.
- Worker.terminate() stops the worker; the 'exit' event signifies completion.
- Workers separate from the main thread: errors in the worker do not immediately stop the main.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.