Go 1.27 reference · Concurrency
Go sync.Mutex and sync.Once Type
Protect shared data so only one goroutine accesses it at a time, and run initialisation exactly once.
Go 1.27
Syntax
func (m *Mutex) Lock() func (m *Mutex) Unlock() func (o *Once) Do(f func())
Parameters
| Parameter | Description |
|---|---|
Lock / Unlock |
Exclusive access; defer Unlock. |
RWMutex |
Many readers or one writer. |
Once.Do / sync.OnceValue |
Lazy initialisation. |
Examples
package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.Mutex
m map[string]int
}
func (c *Counter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[key]++
}
func main() {
c := Counter{m: map[string]int{}}
var wg sync.WaitGroup
for range 100 {
wg.Go(func() { c.Inc("hits") })
}
wg.Wait()
fmt.Println(c.m["hits"])
}
Output
100
Run this on your computer — see “Get Started” for setup.
package main
import (
"fmt"
"sync"
)
func main() {
loadConfig := sync.OnceValue(func() string {
fmt.Println("loading config (once)")
return "port=8080"
})
fmt.Println(loadConfig())
fmt.Println(loadConfig())
}
Output
loading config (once) port=8080 port=8080
Run this on your computer — see “Get Started” for setup.
Related
sync.WaitGroup· Wait for a group of goroutines to finish; WaitGroup.Go (Go 1.25+) starts a goroutine and tracks it in one call.- Go Goroutines and WaitGroup · tutorial