Concurrency in Depth · 16 min · free with an account

Channels vs Mutex

Lesson preview · about 30%

Share memory by communicating, or communicate by sharing memory.

Core idea

Channels move ownership; a mutex shares it. Pick by data flow.

Start with the idea

A channel moves ownership between threads, so there is nothing left to lock and the flow of data is visible in the code. A mutex keeps one copy that several threads mutate in place, which is better when the state is genuinely shared and read far more often than written. Choosing by shape rather than by habit is the answer being looked for.

A channel and a mutex organize ownership in different ways. With a channel, producers send owned messages to a receiver that handles them. This works well when one task can own the state and commands describe the changes. A mutex lets multiple tasks access one shared object, with exclusive access while a guard is held. This works well when callers need immediate coordinated reads or updates to a shared invariant. Neither is universally faster or simpler; the workload and failure path decide.

Consider an order book.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep