This is a creation in Article, where the information may have evolved or changed.
In the previous example we used explicit locking with mutexes to synchronize access to GKFX state across multiple gorout Ines. Another option is to use the built-in synchronization features of Goroutines and channels to achieve the same result. This channel-based approach aligns with Go's ideas of sharing memory by Communivating and have each piece of data owned By exactly 1 goroutine
Package Mainimport ("FMT" "Math/rand" "sync/atomic" " Time") Type read0pstruct{Keyintresp Chanint}type write0pstruct{KeyintValintresp ChanBOOL}func Main () {varOPS Int64 =0reads:= Make (Chan *read0p) writes:= Make (Chan *write0p) go func () {varstate = Make (map[int]int) for { Select { CaseREAD: = <-Reads:read.resp<-State[read.key] CaseWrite: = <-Writes:state[write.key]=Write.val Write.resp<-true } } }() forr: =0; R < -; r++{go func () { for{read:= &read0p{Key:rand. INTN (5), Resp:make (Chanint),} reads<-Read FMT. Println ("<-read.resp:", <-read.resp) Atomic. AddInt64 (&ops,1) } }() } forW: =0; W <Ten; w++{go func () { for{write:= &write0p{Key:rand. INTN (5), Val:rand. INTN ( -), Resp:make (ChanBOOL),} writes<-Write<-Write.resp Atomic. AddInt64 (&ops,1)}} ()} time. Sleep (time. Second) Opsfinal:= Atomic. LoadInt64 (&Ops) fmt. Println ("Ops:", opsfinal)}
329696
Summarize:
1:atomic. AddInt64 an increase in atomicity of one value