Sorry for miss some code, the code should be like this: package main
import ( "sync" "sync/atomic" ) func main() { var n int32 var m sync.RWMutex go func() { for { atomic.LoadInt32(&n) } }() go func() { for { m.RLock() atomic.AddInt32(&n, 1) m.RUnlock() } }() go func() { for { m.Lock() n = 0 m.Unlock() } }() go func() { for { m.Lock() n -= 1 m.Unlock() } }() } Playground link: https://play.golang.org/p/Mrdetw46mXR 在 2019年7月5日星期五 UTC+8下午6:40:32,White Pure写道: > > Hi, > I wrote some code like below these days, and my colleagues and me are > not sure if the code has any concurrent problem. > Can someone help to figure out if the code has any race problem? > Thanks very much! > > Code: > >> package main > > >> import ( > > "sync" > > "sync/atomic" > > ) > > >> func main() { > > var n int32 > > var m sync.RWMutex > > go func() { > > for { > > atomic.LoadInt32(&n) > > } > > }() > > go func() { > > for { > > m.RLock() > > atomic.AddInt32(&n, 1) > > m.RUnlock() > > } > > }() > > go func() { > > for { > > m.Lock() > > n = 0 > > m.Unlock() > > } > > }() > > // do something to keep goroutines running here > > ...... > > } > > > Playground link: https://play.golang.org/p/fRa09l3VQob > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/463a4f5b-ce3f-45a6-bfbd-2ef953fc21c4%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.