Skip to content
Learn Netverks

Lesson

Step 21/36 58% through track

mutex-sync

Mutex and sync

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Mutex and sync: the syntax, patterns, and safety habits you need before advancing in Go.

Teams still ship Mutex and sync in Go codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Mutex and sync in contexts like: Kubernetes ecosystem tools, cloud APIs, and CLI utilities.

Write Go in main.go with package main and func main(), click Run on server—the dev runner runs go run main.go; use fmt.Println for output (requires Go toolchain; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Not everything fits channels. sync.Mutex protects shared memory; sync.WaitGroup waits for goroutines to finish. Prefer channels for ownership transfer; use mutexes for shared caches and counters.

WaitGroup pattern

var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    // work
}()
wg.Wait()

Mutex basics

mu.Lock() / mu.Unlock()—always defer Unlock in functions. sync.RWMutex allows concurrent reads when writes are rare.

Important interview questions and answers

  1. Q: Channels vs mutexes?
    A: Channels for communication and ownership; mutexes for shared state—"share memory by communicating" is the Go proverb, but mutexes are idiomatic for caches.
  2. Q: WaitGroup misuse?
    A: Add/Done mismatch causes hang or panic—match counts carefully; call Add before starting goroutine.

Self-check

  1. What does WaitGroup.Wait block on?
  2. Why defer mu.Unlock()?

Pitfall: Copying a sync.Mutex by value breaks locking—pass pointers or keep mutexes in structs accessed by pointer.

Interview prep

Channels vs mutex?

Channels for communication; mutexes for protecting shared mutable state like caches.

WaitGroup pitfall?

Add/Done mismatch hangs or panics—call Add before starting goroutine.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Mutex vs channel?
  • RWMutex when?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump