Skip to content

Goroutine Counter

Build a thread-safe counter that can be safely incremented from multiple goroutines.

When multiple goroutines access shared state concurrently, you need synchronization to prevent race conditions. This exercise focuses on the channel ownership pattern: a single goroutine owns the value, and every other goroutine talks to it over channels (“don’t communicate by sharing memory; share memory by communicating”).

Implement a Counter struct with:

  1. A method to increment the counter
  2. A method to get the current value
  3. Synchronization that makes both safe under concurrent use

The counter should work correctly even when incremented from 100 concurrent goroutines.

The tests are purely behavioural, so any concurrency-safe implementation passes - a sync.Mutex or sync/atomic counter is a perfectly good answer and is what you would usually reach for in production. The hints and the reference solution deliberately walk through the channel-ownership version instead, because that is the pattern this chapter is teaching; try it that way first, then compare it with the mutex version.

Thread-Safe Counter

~10 mineasy

Implement a counter that can be safely used from multiple goroutines

  • Channel-based synchronization: Using channels to serialize access to shared state
  • Select statement: Handling multiple channel operations
  • Ownership pattern: One goroutine “owns” the state and communicates via channels
  • Picking a tool: Channel ownership shines when the owner does real work per message; for a plain counter a sync.Mutex (or sync/atomic) is simpler and faster - both are correct here