Table of Contents

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?

When to use

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

Hard words (English)