CodePark/ questions / Concurrency primitives & race conditions
START PRACTICINGPRACTICE
Backend question · OS, networking & Linux › Concurrency primitives & race conditions

What is the difference between concurrency and parallelism? Where does Node.js fit?

Concurrency means a program makes progress on several tasks during the same period. The tasks take turns, so their steps are interleaved. Parallelism means tasks really run at the same instant, on different CPU cores.

A short way to remember it: concurrency is about dealing with many things at once. Parallelism is about doing many things at once. One core can run tasks concurrently by switching between them. But one core can't run them in parallel.

Node.js is a good example. One thread runs your JavaScript. Yet it serves thousands of requests concurrently. Why? Each request spends most of its time waiting on I/O, such as a database query or a network call. While one request waits, the event loop (Node's loop that picks the next ready piece of work) runs other work. Your JavaScript itself does not run in parallel.

For CPU-heavy work, you need parallelism to use several cores. Your options are:

  • worker threads
  • multiple processes
  • several instances behind a load balancer
  • Concurrency means interleaved progress on many tasks, while parallelism means tasks run at the same instant.
  • Concurrency is possible on one core, but parallelism needs several cores.
  • Node handles I/O concurrency on one JavaScript thread by using the event loop.
  • Parallelism for CPU-heavy work needs worker threads or more processes.