Concurrent Programming Deep Dive
Understand threads, processes, race conditions, synchronization, and parallelism vs concurrency.
What you'll learn
- Concurrency vs parallelism distinction
- Race conditions and data races
- Synchronization primitives: locks, semaphores
- Deadlock conditions and prevention
Concept
Concurrent Programming Deep Dive
Concurrency is dealing with multiple things at once; parallelism is doing multiple things at once. A single-core machine can be concurrent (time-slicing) but not parallel. A multi-core machine can be both. Concurrency is about structure; parallelism is about execution.
Processes vs Threads
A process is an independent program with its own memory space. A thread is a unit of execution within a process, sharing memory with other threads. Threads are lighter but risk data races because they share memory. Processes are isolated but heavier.
Race Conditions
A race condition occurs when the outcome depends on the timing of thread execution. Classic example: two threads increment a shared counter. If both read the value 5, both write 6 - one increment is lost. The fix is atomicity: make read-modify-write indivisible using a lock or atomic operation.
Synchronization Primitives
Mutex (lock): only one thread can hold it at a time. Semaphore: allows N threads simultaneously. Condition variable: threads wait until a condition is signaled. Atomic operations: hardware-level indivisible operations (compare-and-swap).
Deadlock
Deadlock occurs when threads wait on each other in a cycle. The four Coffman conditions must all hold: mutual exclusion, hold-and-wait, no preemption, circular wait. Break any condition to prevent deadlock: acquire locks in a consistent global order.
JavaScript Concurrency
JavaScript is single-threaded but concurrent via the event loop. Parallelism comes from Web Workers or async I/O. SharedArrayBuffer and Atomics enable true shared-memory parallelism between workers.
Example
// Race condition demonstration (single-threaded simulation)
let counter = 0;
// Simulate two threads interleaving
counter = 0;
const t1a = counter; // 0
const t2a = counter; // 0 (read before t1 writes)
counter = t1a + 1; // 1
counter = t2a + 1; // 1 - should be 2!
console.log('Unsafe:', counter); // 1 (lost update)
// Fix: atomic increment
counter = 0;
const atomicIncrement = () => { counter = counter + 1; };
atomicIncrement(); atomicIncrement();
console.log('Safe:', counter); // 2
// Producer-consumer with a simple queue
const buffer = []; const MAX = 3;
function produce(item) { if (buffer.length < MAX) { buffer.push(item); console.log('Produced:', item); } else console.log('Buffer full'); }
function consume() { if (buffer.length > 0) { console.log('Consumed:', buffer.shift()); } else console.log('Buffer empty'); }
produce(1); produce(2); produce(3); produce(4);
consume(); consume();
The unsafe increment interleaves read and write, losing an update. The atomic version does read-modify-write in one step. The producer-consumer uses a bounded buffer.
Try it
- Crontab Generator
Scheduled jobs are concurrent - see how timing and ordering interact.
Common mistakes
The mistake
Forgetting to lock a shared resource, causing a data race.
The fix
Any shared mutable state accessed by multiple threads needs synchronization. Even a simple counter increment is not atomic.
The mistake
Acquiring locks in different orders in different code paths.
The fix
If thread A locks X then Y, and thread B locks Y then X, deadlock is possible. Always acquire locks in a consistent global order.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.