ProgramGuru

Channels vs Mutexes

Start with Channels vs Mutexes

In this lesson, explore channels vs mutexes through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of channels vs mutexes.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Use channels when tasks naturally exchange ownership of messages or need synchronization around a pipeline. Use mutexes when goroutines need brief coordinated access to an existing shared data structure.

Neither mechanism is universally safer or faster. The strongest design makes data ownership clear and minimizes shared mutable state.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for channels vs mutexesChoose the simplest correct ownership and synchronization model.Shared mapStep 1Mutex guards updatesStep 2Wait for workersStep 3Read final totalsStep 4Choose the simplest correct ownership and synchronization model.
Choose the simplest correct ownership and synchronization model.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"sync"
)

func main() {
	var mu sync.Mutex
	totals := map[string]int{}
	var wg sync.WaitGroup
	for _, name := range []string{"a", "b", "a"} {
		wg.Add(1)
		go func(key string) { defer wg.Done(); mu.Lock(); totals[key]++; mu.Unlock() }(name)
	}
	wg.Wait()
	fmt.Println("a:", totals["a"], "b:", totals["b"])
}

Output

a: 2 b: 1

Trace what the program does

The shared map is protected by one mutex, which is straightforward for short updates. Wait finishes the work before the two deterministic lookups.

Avoid common mistakes

  • Native maps cannot be concurrently written without synchronization.
  • A channel may add needless complexity when protecting a short map update.

Try it yourself

Rewrite the map update so one goroutine owns the map and receives keys through a channel.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What primarily determines whether to use channels or mutexes?
Choose one answer. You can try again.

Answer and explanation

Data ownership and required coordination

Correct. The shared map is protected by one mutex, which is straightforward for short updates.

What you should remember

You have practiced Channels vs Mutexes in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Goroutine Leaks →