Goroutine Counter
Build a thread-safe counter that can be safely incremented from multiple goroutines.
Background
Section titled “Background”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”).
Your Task
Section titled “Your Task”Implement a Counter struct with:
- A method to increment the counter
- A method to get the current value
- 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
Implement a counter that can be safely used from multiple goroutines
Key Concepts
Section titled “Key Concepts”- 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(orsync/atomic) is simpler and faster - both are correct here