“What if two goroutines want to touch the same variable?”
“How do I protect it?”
That’s where Go’s sync package comes in! Think of it as your security guard for shared data.
If two goroutines access (or change) the same variable at the same time…
💥 BOOM — you get a race condition.
Use a mutex (short for "mutual exclusion") to lock access.
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
count := 0
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
mu.Lock()
count++
mu.Unlock()
wg.Done()
}()
}
wg.Wait()
fmt.Println("Final count:", count)
}Without mu.Lock(), you’ll get a wrong value (not 1000).
With the lock, it works properly. ✅
Tool | What It Does
sync.Mutex | Locks shared data
sync.RWMutex | Read/Write lock (multiple reads, one write)
sync.Once | Run something only once
sync.WaitGroup | Wait for goroutines to finish
sync.Map | Thread-safe map (no need to lock)var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("Hello from goroutine")
}()
wg.Wait()This waits for the goroutine to finish before continuing.
Go’s normal map isn’t safe for goroutines. Use this instead:
var m sync.Map
m.Store("name", "Ashraf")
value, _ := m.Load("name")
fmt.Println(value) // Ashrafsyncis Go’s way to manage safe sharingUse it when multiple goroutines touch the same variable
Lock what must not be touched together
Always unlock when done!
No posts

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.