Concurrency in Depth · 16 min · free lesson

Channels vs Mutex

Share memory by communicating, or communicate by sharing memory.

Core idea

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

Lesson map: a spawned thread sending a computed value over an mpsc channel to a receiver, above the rule that channels move ownership and a mutex shares it.
Desktop std channel fragment: provide compute and a surrounding function; OS-thread support is target-dependent.

Understand it

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 access in turn, which fits when the state is genuinely shared and each update must see it whole. It also serializes readers, so read-mostly state may suit an RwLock or a swapped Arc better. 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. A single owner task receiving add and cancel commands can serialize updates without exposing internal mutable state. If many workers only read an immutable configuration and rarely replace it, a read-oriented sharing strategy may be clearer than funneling every read through messages. A mutex around a small counter is straightforward, though an atomic may fit that narrow operation. Name the invariant before choosing the primitive.

Mention backpressure and shutdown in an interview answer. An unbounded channel can grow without limit if producers outpace the receiver. A bounded channel makes senders wait or fail when capacity fills. A receiving loop ends only after all sender handles are gone; an accidentally retained clone can keep it waiting. A mutex guard should not be held while doing slow I/O or calling unknown code. Show the interviewer how each design makes a particular failure visible, then explain the tradeoff in latency, ordering, and complexity.

When a result is required from the owner task, include a reply channel or request identifier. That extra protocol cost can make a simple mutex more attractive for a tiny local operation. Conversely, a channel may make shutdown and audit logging cleaner because all state changes pass through one place.

Interview follow-up: Explain why per-producer order does not necessarily define a meaningful global order for simultaneous requests.

Read the code

let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
    tx.send(compute()).unwrap();
});
let value = rx.recv().unwrap();

Desktop std channel fragment: provide compute and a surrounding function; OS-thread support is target-dependent.

Practice starter

// Several producers submit jobs to one worker.
// The worker processes each accepted message.
// The input rate can exceed the worker rate.

Practise this code in Playground ↗

Try it

Pick channel or mutex for a metrics counter and for a work queue.

What success looks like: Each choice names who owns the data and how often it is written.

Check your understanding

What extra contract is needed for a multi-producer work queue?

Reveal the answer
  1. A channel guarantees one global real-time ordering for concurrent senders.
  2. Define capacity, overload behaviour and the required ordering between producers.
  3. A mutex-protected Vec automatically supplies capacity limits and wakeups.

A channel models transfer, but does not eliminate capacity, shutdown or ordering design. A shared-state API can also be appropriate for a different access pattern.

Go deeper

Common misconception: A mutex-protected Vec automatically supplies capacity limits and wakeups.

A Mutex around a Vec supplies only exclusive access. The Vec still grows without a limit, and waking a waiting worker needs something more, such as a Condvar or a bounded channel.

  1. Identify the contract: Share memory by communicating, or communicate by sharing memory.
  2. Trace the concrete example: The value moves; no lock is needed on either side.
  3. Test the changed constraint: Explain why per-producer order does not necessarily define a meaningful global order for simultaneous requests.

Transfer challenge: Explain why per-producer order does not necessarily define a meaningful global order for simultaneous requests.

Connections

  • Deadlocks: What the borrow checker does not prevent
  • Async vs Threads: Waiting versus computing
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Channels vs Mutex (courseId "interview", lessonId "q-channels-vs-mutex")
Link: https://crabrix.com/learn/interview/q-channels-vs-mutex/
Goal: Channels move ownership; a mutex shares it. Pick by data flow.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-channels-vs-mutex) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.