Lesson 16 of 60 · Go
Atomic Operations & Mutexes
Duration: 20 minutes
Synchronization Primitives
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
sync.Mutex
var mu sync.Mutex
counter := 0
for i := 0; i < 100; i++ {
go func() {
mu.Lock()
counter++
mu.Unlock()
}()
}
sync.RWMutex (read‑write lock)
var rw sync.RWMutex
// multiple readers
rw.RLock(); defer rw.RUnlock()
// exclusive writer
rw.Lock(); defer rw.Unlock()
Atomic package (sync/atomic)
var ops uint64
atomic.AddUint64(&ops, 1)
val := atomic.LoadUint64(&ops)
When to use which?
- Mutex for simple critical sections.
- RWMutex when reads dominate writes.
- Atomic for lock‑free counters and flags.