Table of Contents

sync package

What is it?

`sync` is a Go standard library package that provides basic synchronization primitives for coordinating goroutines and protecting shared data.

What is it used for?

Common types (overview)

Quick examples

Mutex

var mu sync.Mutex
mu.Lock()
// critical section
mu.Unlock()

RWMutex

var mu sync.RWMutex
mu.RLock()
// read-only section
mu.RUnlock()
 
mu.Lock()
// write section
mu.Unlock()

WaitGroup

var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    // work
}()
wg.Wait()

Once

var once sync.Once
once.Do(func() {
    // init exactly once
})

Cond

mu := sync.Mutex{}
cond := sync.NewCond(&mu)
_ = cond

When to use sync vs channels

Notes / pitfalls

Hard words (English)