This is a creation in Article, where the information may have evolved or changed.
In the previous example we saw how to manage simple counter state using atomic operations. For more complex state we can use a mutex to safetly access data across multiple Goroutines
Package Mainimport ("FMT" "Math/rand" "Runtime" "Sync" "sync/atomic" " Time") Func main () {varstate = Make (map[int]int) varMutex = &sync. mutex{}varOPS Int64 =0 forr: =0; R <= -; r++{go func () {total:=0 for{key:= Rand. INTN (5) mutex. Lock () Total+=State[key] Mutex. Unlock () Atomic. AddInt64 (&ops,1) runtime. Gosched ()}} ()} forW: =0; W <Ten; w++{go func () { for{key:= Rand. INTN (5) Val:= Rand. INTN ( -) mutex. Lock () State[key]=Val Mutex. Unlock () Atomic. AddInt64 (&ops,1) runtime. Gosched ()}} ()} time. Sleep (time. Second) Opsfinal:= Atomic. LoadInt64 (&Ops) fmt. Println ("Ops:", opsfinal) mutexes. Lock () fmt. Println ("State :", state) mutex. Unlock ()}
OPS: 4738109state:map[0:2:3: 1:4:7]
Summarize:
1: ...