Go by Example

Mutexes

Use sync.Mutex to safely share state across goroutines when atomic operations are not enough.

A mutex is a lock that lets goroutines take turns using the same data. A goroutine is a function that can run while its caller continues. Use sync.Mutex when only one goroutine at a time may read or change shared data.

Lock before changing the counter and unlock when the method returns. Multiple goroutines can safely call Inc.

package main
 
import (
    "fmt"
    "sync"
)
 
type Counter struct {
    mu    sync.Mutex
    value int
}
 
func (c *Counter) Inc() {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.value++
}
 
func (c *Counter) Value() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.value
}
 
func main() {
    c := new(Counter)
    var wg sync.WaitGroup
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            c.Inc()
        }()
    }
    wg.Wait()
    fmt.Println(c.Value())
}

In production

Keep the lock near the data it protects. defer schedules the unlock to run when the current function returns. One mutex can protect several fields that must change together. Keep the time the lock is held short so other goroutines do not wait longer than needed.

Enjoyed this? Get more software craft delivered to your inbox.