Standard library / sync
sync.Mutex
Zero value is unlocked. Protect every access to shared mutable state with the same mutex. Never copy after first use. Expected stdout: '3\n'.
Formal Syntax & Structure
go syntaxgo
type Mutex struct {}Working Example
Example Snippetgo
package main
import ( "fmt" "sync")
func main() { var m sync.Mutex var wg sync.WaitGroup n := 0 for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done(); m.Lock(); n++; m.Unlock() }() } wg.Wait() fmt.Println(n)}