0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Asynchronous I/O
Actors and Message Passing
Concurrent components can communicate in two basic ways: by reading and writing shared memory, protected by locks and atomics, or by sending each other messages, with each component owning its own state. This section contrasts the two approaches, explains why message passing removes whole classes of bugs, and shows what it costs in exchange.
Two ways to cooperate
Every lesson so far in this course has used shared memory. Threads read and write the same variables, and correctness depends on locks, atomics and memory ordering to make those accesses safe. This model is natural on a single machine, where all threads see the same address space, and it is very fast when contention is low. It is also the source of nearly every concurrency bug covered so far: races, lost updates, visibility problems, deadlocks and priority inversion all come from several threads touching the same state. Message passing takes the opposite approach. Each component owns its state privately, and no other component can touch it. Components cooperate only by sending messages, which the owner processes one at a time. Since only one component ever accesses a given piece of state, and it does so sequentially, there is nothing to race on and no lock to forget.
The Go proverb puts it concisely: do not communicate by sharing memory; instead, share memory by communicating. A value sent in a message is handed over from sender to receiver, and the sender should not touch it afterwards, so at any moment exactly one component owns it. Rust enforces this rule at compile time through ownership: sending a value on a channel moves it, and the compiler rejects any later use by the sender. Erlang enforces it by copying every message, so sender and receiver never share memory at all.
What message passing removes
Giving every piece of state a single owner eliminates data races, since no two components access the same memory concurrently. It removes the need to reason about memory ordering for that state, since a message send and receive establishes a happens before relation: everything the sender did before sending is visible to the receiver after receiving. It removes lock ordering problems, since there are no locks around the state. And it makes ownership explicit in the design: to find out who can change a value, look for the component that owns it, rather than searching every place that might take a particular lock. The result is a system that is easier to reason about locally, because each component can be understood as a sequential program that responds to messages.
What it does not remove
Message passing does not eliminate concurrency problems; it changes their form. Components can still deadlock, for example when each waits for a reply from the other. Messages can arrive in orders the designer did not expect, producing logical races: two clients both send reserve seat messages, and whichever arrives first wins, which may or may not be the intended behaviour. Mailboxes can fill up when a component receives messages faster than it processes them, which is the producer consumer problem in a new setting, and backpressure must be designed in. And state that must be consistent across several components now needs a protocol, since no single lock can protect it all. The bugs are usually easier to find, because they appear at well defined message boundaries, but they still exist.
The cost of messages
Messages cost more than shared memory accesses. Sending a message means allocating or copying it, putting it in a queue that itself needs synchronization, and waking the receiver if it is idle, which can mean a context switch. A shared counter incremented with an atomic instruction costs a few nanoseconds; sending an increment message to an actor and having it processed costs hundreds of nanoseconds to microseconds. For state accessed millions of times per second by many threads, shared memory with careful synchronization is faster. For state with complex invariants touched by many components, the clarity of message passing usually outweighs the cost. Many systems mix both: message passing between components and shared memory, carefully controlled, inside performance critical ones.
A short history
Message passing is older than most shared memory techniques. Hoare described Communicating Sequential Processes in 1978, and the occam language built on it ran on the transputer chips of the 1980s, which had hardware links between processors and no shared memory at all. Hewitt introduced the actor model in 1973 as a model of computation for artificial intelligence research. Erlang, developed at Ericsson from 1986 for telephone switches, applied actor style processes to systems that needed to run for years without stopping, and the AXD301 switch built with it became famous for very high availability. Message passing then fell out of the mainstream as shared memory multiprocessors and threads dominated through the 1990s and 2000s, until multicore processors and distributed systems revived interest. Go, released in 2009, brought CSP channels to a wide audience, and Akka brought actors to the JVM in the same period.
Isolation at different scales
The same choice between sharing and messaging appears at every level of a system. Inside a process, threads can share memory or use channels and actors. Between processes on one machine, they can share memory through mapped regions or communicate through pipes and sockets. Between machines, there is no shared memory at all, and every interaction is a message, whether it is an HTTP request, a gRPC call or an event on a broker. Designs that use message passing inside a process often move more easily to a distributed setting, because the boundaries between components are already explicit and every interaction already goes through a well defined interface. Designs built on shared memory usually need significant restructuring before parts can run on different machines, because the hidden coupling through shared state must first be made visible.
Immutable data as a middle ground
There is a middle ground between sharing mutable state and copying everything: sharing immutable data. If a value can never change after it is created, any number of threads can read it at the same time without synchronization, because there is nothing to race on. Functional languages such as Clojure, Haskell and Scala lean heavily on this, using persistent data structures that produce a new version on every update while sharing most of their structure with the old one, so updates are cheap and old versions remain valid for readers that still hold them. A common pattern combines this with a single atomic reference: readers load the current immutable snapshot, and a writer builds a new version and swaps the reference with compare and swap. Configuration, routing tables and feature flags are often managed this way, giving readers lock free access to a consistent snapshot.
The choice is therefore rarely all or nothing. Most real systems use message passing at the boundaries between components and shared memory, carefully encapsulated, inside the few components where performance demands it, keeping the shared parts small enough to review thoroughly.
Whichever model is chosen, the essential step is to decide, for every piece of mutable state, exactly which components may change it and how they coordinate.
Message passing replaces locks with ownership: one component owns each piece of state and others communicate with it by sending messages. This removes data races and lock ordering bugs, but not deadlock, unexpected message order or mailbox overflow. It costs more per operation than shared memory, so use it for clarity at component boundaries and keep hot paths fast.