User Tools

Site Tools


go:concurrency:mutex

sync.Mutex

What is it?

`sync.Mutex` is a mutual exclusion lock used to protect shared data from concurrent access.

What is it used for?

  • Prevent data races when multiple goroutines read/write the same variable/structure.
  • Protect critical sections (a block of code that must not run concurrently).

When to use

  • You have shared mutable state (e.g., map, slice, struct fields) accessed by multiple goroutines.
  • You need simple, explicit locking around updates.

Example

package main
 
import "sync"
 
type Counter struct {
    mu sync.Mutex
    n  int
}
 
func (c *Counter) Inc() {
    c.mu.Lock()
    c.n++
    c.mu.Unlock()
}
 
func (c *Counter) Value() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.n
}

Notes / pitfalls

  • Always `Unlock()` (use `defer` for safety).
  • Avoid long work while holding the lock (it reduces throughput).
  • Do NOT copy a struct containing a `Mutex` after first use.

Hard words (English)

  • mutex /ˈmjuːtɛks/: khóa loại trừ
  • mutual exclusion /ˈmjuːtʃuəl ɪkˈskluːʒən/: loại trừ lẫn nhau
  • shared data /ʃerd ˈdeɪtə/: dữ liệu dùng chung
  • concurrent /kənˈkɝːənt/: đồng thời
  • critical section /ˈkrɪtɪkəl ˈsekʃən/: vùng code cần khóa
  • pitfall /ˈpɪtfɔːl/: “bẫy” thường gặp
  • throughput /ˈθruːpʊt/: thông lượng
go/concurrency/mutex.txt · Last modified: by phong2018