User Tools

Site Tools


go:concurrency:sync

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?

  • Protect shared resources from concurrent access (locks).
  • Wait for multiple goroutines to finish.
  • Run one-time initialization safely.
  • Coordinate goroutines based on conditions.

Common types (overview)

  • `Mutex`: mutual exclusion lock (one goroutine at a time).
  • `RWMutex`: read/write lock (many readers or one writer).
  • `WaitGroup`: wait for a set of goroutines to finish.
  • `Once`: run a function exactly once.
  • `Cond`: condition variable (wait/signal on state changes).
  • `Map`: concurrent map (special use cases; read docs carefully).
  • `Pool`: object pool to reduce allocations (advanced/perf).

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

  • Use `sync.Mutex`/`RWMutex` when you have shared mutable state (maps/slices/struct fields).
  • Use channels when you want to pass data between goroutines and structure concurrency as message passing.
  • Both are valid; choose the clearest, safest design.

Notes / pitfalls

  • Do NOT copy structs containing `Mutex`, `RWMutex`, `WaitGroup`, `Once`, or `Cond` after first use.
  • Keep critical sections small (avoid slow I/O while holding locks).
  • Prefer `context` for cancellation/timeouts; `sync` does not cancel goroutines.

Hard words (English)

  • synchronization /ˌsɪŋkrənəˈzeɪʃən/: đồng bộ hoá
  • primitive /ˈprɪmətɪv/: thao tác/công cụ nền tảng
  • coordinate /koʊˈɔːrdɪneɪt/: điều phối
  • concurrent /kənˈkɝːənt/: đồng thời
  • shared resource /ʃerd rɪˈzɔːrs/: tài nguyên dùng chung
  • critical section /ˈkrɪtɪkəl ˈsekʃən/: vùng code cần khóa
  • condition variable /kənˈdɪʃən ˈveriəbəl/: biến điều kiện
  • allocation /ˌæləˈkeɪʃən/: cấp phát bộ nhớ
  • mutable /ˈmjuːtəbəl/: có thể thay đổi
  • message passing /ˈmesɪdʒ ˈpæsɪŋ/: truyền thông điệp
  • cancellation /ˌkænsəˈleɪʃən/: huỷ
go/concurrency/sync.txt · Last modified: by phong2018