Skip to content

Concurrency

Concurrency is about dealing with many things at once; parallelism is about doing many things at once. They are different problems with different tools, and interviewers use them to check whether you understand what actually happens when two pieces of code run “at the same time”.

Concurrency is structuring a program so multiple tasks make progress without waiting for each other; parallelism is executing them at the same instant on multiple cores. One core can be concurrent but not parallel. Threads share memory and need synchronisation; processes do not and communicate via IPC. Race conditions come from unsynchronised shared mutable state. Locks prevent races but introduce deadlock and contention. Async I/O avoids blocking by yielding while waiting, without a thread per connection.

Concurrency Parallelism
Definition Tasks interleave; progress on many at once Tasks run simultaneously
Hardware One core is enough Multiple cores required
Goal Responsiveness, throughput while waiting Speed from raw computation
Failure mode Race conditions, deadlock Also races, plus scaling limits
Example A server holding 1,000 idle connections Matrix multiplication on 8 cores

A single-core machine running three threads is concurrent but not parallel: the scheduler switches between them. Eight cores running eight computations is both.

Threads Processes
Memory Shared address space Isolated
Creation cost Low (KBs, microseconds) High (MBs, milliseconds)
Communication Direct memory access Pipes, sockets, shared memory
Fault isolation A crash can take down the process A crash kills one process
Synchronisation Required Mostly unnecessary

Rule of thumb: threads for I/O-bound work that shares state, processes for CPU-bound work and isolation. Chrome, Postgres and nginx all use process pools for exactly this reason.

A race is when the result depends on the interleaving of operations. The canonical case is a read-modify-write on shared data, where counter += 1 is really read, add, write.

counter = 0
threads = 10.times.map { Thread.new { 1_000.times { counter += 1 } } }
threads.each(&:join)
puts counter # almost never 10_000
mutex = Mutex.new
counter = 0
threads = 10.times.map { Thread.new { 1_000.times { mutex.synchronize { counter += 1 } } } }
threads.each(&:join)
puts counter # 10_000

If the critical section is a single arithmetic operation, an atomic primitive (Concurrent::AtomicFixnum in Ruby, AtomicInteger in Java) is cheaper than a mutex: hardware compare-and-swap, no lock.

  • Mutex: one thread in the critical section at a time.
  • Read-write lock: many readers, one writer. Wins when reads vastly outnumber writes.
  • Semaphore: up to N concurrent holders — a connection pool is a counting semaphore.
  • Condition variable: wait for a predicate without busy-looping.

Contention serialises work, and a fine-grained lock in a hot path can be slower than a coarse one. Measure before splitting locks, and never call slow external code while holding one.

Four conditions must all hold: mutual exclusion, hold-and-wait, no preemption, circular wait. Break any one and deadlock is impossible; the practical fix is a global lock ordering, derived from object identity rather than call order. Related failures: livelock (retrying forever, never progressing), starvation (one thread never scheduled), priority inversion.

An operation is atomic if it appears indivisible to other threads. Even then, threads may see stale values because of CPU caches and compiler reordering; languages expose barriers, volatile or synchronized to control it. Ruby’s GVL gives strong visibility within a process; the JVM and Go make it explicit.

Blocking I/O parks a thread while the kernel waits. Async I/O registers interest with an event loop and resumes the task when data arrives, so one thread can manage thousands of idle connections — the C10k problem. The cost: async code is harder to debug, one slow synchronous call blocks everything, and CPU-bound work still needs threads or processes.

Runtime Model Real parallelism?
Ruby (MRI) OS threads + GVL No for bytecode; yes for I/O and C extensions
Ruby (JRuby/TruffleRuby) OS threads, no GVL Yes
Ruby Ractors Isolated actors Yes, still limited
JavaScript Event loop + libuv pool No for JS; yes for workers and I/O
BEAM (Elixir/Erlang) Preemptive lightweight processes Yes, across all cores
Go Goroutines on an M:N scheduler Yes

Ruby’s GVL lets one thread execute Ruby bytecode at a time. Threads still help because the GVL is released during I/O and inside many C extensions. For CPU parallelism: processes (fork, Puma workers, Sidekiq processes) or Ractors.

JavaScript’s event loop runs one callback at a time; async/await is syntax over promises, not threads. Long synchronous work blocks timers and I/O callbacks; worker_threads is the escape hatch.

  1. If Ruby has a GVL, why do threads still help a Rails app?
  2. How would you investigate a race that only appears in production?
  3. What is the difference between a mutex and a semaphore?
  4. When would you choose async I/O over a thread pool?
  5. What breaks an event loop?
  • Equating concurrency with parallelism. The most common interview error on this topic.
  • Thinking async/await is multithreading. It is cooperative scheduling.
  • Assuming more threads always help. Contention and context switches say otherwise.
  • Assuming the GVL makes hashes thread-safe. hash[k] ||= [] still interleaves.
  • Holding a lock across slow I/O. Hold locks for the minimum scope.