Coding/Learn/go/go sync mutex atomic
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnMutexes, RWMutex & Atomic Primitives
17 / 20 0%
Lesson 17 of 20
14 mins read

Mutexes, RWMutex & Atomic Primitives

PreviousNext Lesson
In Plain English

When channels are overkill for simple shared state, Go standard library provides low-level synchronization primitives: sync.Mutex, sync.RWMutex for read-heavy workloads, and sync/atomic for lock-free hardware atomics.

The Mental Model

"A Mutex is a bathroom key on a heavy wooden block—only one person can hold it and enter at a time. An RWMutex allows 100 people to read a signboard together, but locks everyone out when an editor updates the sign."

Deep Dive: How It Works

sync.Mutex: Mutual exclusion lock. mu.Lock() blocks until previous owner calls mu.Unlock().

sync.RWMutex: Allows multiple simultaneous readers (RLock) or one exclusive writer (Lock).

sync/atomic: Hardware CPU instructions (atomic.Int64) for zero-allocation, lock-free operations.

Syntax Blueprint

var mu sync.Mutex
mu.Lock()
defer mu.Unlock()
sharedCounter++

Acquire lock with mu.Lock(), defer mu.Unlock() immediately, and update shared state.

PointCore Rules to Remember

Point star
Critical Sections: Keep code between Lock() and Unlock() as brief as possible.
Point star
Defer Unlock: Always defer mu.Unlock() to prevent permanent deadlocks on early returns or panics.
Point star
Never Copy Mutexes: Pass structs containing mutexes by pointer, never by value.

Common Beginner Traps & How to Fix Them

Mistake:Passing a struct containing a sync.Mutex by value into a function.

Why it happens: Copying a mutex copies its internal locked state, breaking synchronization.

How to fix: Pass the struct as a pointer (*SafeStruct).

Pro Tip: Use go test -race to detect data races in your concurrent code automatically during testing.

Live Interactive Example

Hit Run Code to see it live
Thread-Safe Counter with sync.Mutex
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Output Console
Click "Run Code" to view the rendered output.
How it works: 5 goroutines each incremented 100 times. Mutex locks prevented race conditions.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Lock-Free Counter with sync/atomic

  • PointUse sync/atomic atomic.Int64 to implement a thread-safe counter.
  • PointSpawn 4 goroutines, each calling counter.Add(25).
  • PointWait with sync.WaitGroup and print "Atomic Sum: %d".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates