Overview
This lecture explains how JavaScript, usually single-threaded, can achieve multi-threaded execution using workers, leading to significant performance gains for CPU-intensive tasks.
JavaScript Execution Model
- JavaScript is a high-level, single-threaded, garbage-collected, interpreted or JIT-compiled, prototype-based, dynamic, multi-paradigm language.
- By default, JavaScript runs code on a single CPU core (the main thread).
Concurrency vs Parallelism
- Concurrency allows overlapping tasks but only one runs at a time (like a single chef multitasking).
- Parallelism executes multiple tasks at the same time across multiple CPU cores (like several chefs working together).
Multi-threading in JavaScript
- JavaScript can use multi-threading with Web Workers (browser) or worker threads (Node.js).
- Multi-threading is best for CPU-intensive tasks, not I/O operations.
- Multi-threading distributes work across available CPU cores but doesn't speed up all types of tasks.
Implementing Workers in Node.js
- Move CPU-heavy code (e.g., heavy loops) from the main thread into a separate worker.js file.
- Use the worker_threads module to create workers and communicate between threads.
- Split large tasks into chunks, assign each chunk to a worker, and handle results via message passing.
Performance Gains
- Running tasks on the main thread took ~44 seconds.
- Using 2 workers halved the time (~20 seconds); doubling workers continued increasing CPU usage and reducing execution time.
- With 16 workers (fully utilizing all cores), execution time dropped to 4.7 seconds (10x faster).
- Adding more workers than cores does not yield further speed improvements.
Main Thread Blocking Demo
- Running a
while(true){} loop on the browser main thread will freeze the page, underscoring single-thread limitations.
Key Terms & Definitions
- Main thread โ the single thread where JavaScript normally executes code.
- Worker โ a separate thread for running code in parallel, off the main thread.
- Concurrency โ overlapping execution of tasks on a single thread.
- Parallelism โ simultaneous execution of multiple tasks across CPU cores.
- CPU-intensive โ operations that heavily use the processor (e.g., calculations, image processing).
- I/O-intensive โ tasks waiting on input/output (disk, network), not limited by CPU speed.
- Chunkify โ splitting a dataset into equal parts for distribution among workers.
Action Items / Next Steps
- Create
index.js and worker.js files to practice using worker threads in Node.js.
- Use the performance module to measure execution times.
- Experiment with varying the number of parallel workers to observe performance differences.