Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

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.

Info

Avoid mixing mutexes and atomic operations on the same variable – it leads to undefined behavior.

Previous: Concurrency Patterns: Worker PoolsNext: The `context` Package – Cancellation & Timeouts