Go Developer interview question

When do you use channels versus mutexes?

Use channels to transfer ownership or coordinate a stream of values; use a mutex to protect shared mutable state. Channels are not automatically simpler when several operations must update one invariant atomically.

Direct answer

What a strong answer covers

How it works

Channels express ownership transfer and coordination: a producer hands values to a consumer, a done channel signals completion, a semaphore channel bounds concurrency. A mutex protects an invariant that several goroutines read and update in place. The choice follows the data flow: if the value moves between stages, use a channel; if the value stays put and is updated, lock it. Mixing the two for a single shared structure usually produces the hardest bugs.

Example

A worker pipeline communicates jobs over channels; a shared map of counters is usually clearer behind a mutex. Rewriting the counter map as a goroutine that owns it and receives increment messages is possible, but it adds latency and a goroutine to shut down for no gain in clarity.

Common mistakes

  • Using a channel as a lock and forgetting the buffer size changes its semantics.
  • Protecting several related fields with separate mutexes so the invariant can still be observed half-updated.
  • Holding a mutex while sending on a channel, which can deadlock if the receiver needs the same lock.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
Go Developer interview questions