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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func (m *Mutex) Lock()   func (m *Mutex) Unlock()   func (o *Once) Do(f func())

Parameters

ParameterDescription
Lock / Unlock Exclusive access; defer Unlock.
RWMutex Many readers or one writer.
Once.Do / sync.OnceValue Lazy initialisation.

Examples

Example 1
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.

sync.OnceValue
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.

Was this page helpful?