Channels or Mutexes?

Patrick Kelly
1 min readMar 12, 2018

--

Although in go there is the awesome tool of channels to facilitate concurrent programs, sometimes using a mutex is the right thing to do.

In Concurrency in Go, the author offers a concise decision tree to determine if you should use mutexes or channels. Here is the logic translated into idiomatic go:

if performanceCriticalSection {
return USE_MUTEXES
}
if transferingDataOwnership {
return USE_CHANNELS
}
if guardingInternalStateOfStruct {
return USE_MUTEXES
}
if coordinatingMultiplePiecesOfLogic {
return USE_CHANNELS
}
return USE_MUTEXES

Of course there is more explanation of how to judge these decision points. (The most important being that just because you want a high performance program does not mean that every section is a performance critical section!)

You can play with the inputs and run the program in the playground.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Patrick Kelly
Patrick Kelly

Written by Patrick Kelly

Web/database engineer/gopher. Cycling, photos, yada, yada.

No responses yet

Write a response