Even if you do this, the code still has a “race” as there is no way to logically reason as to the eventual outcome or purpose. You can take out all of the concurrent controls and you’ll have the same program/result (although the race detector will report an issue) - no claims can be made about any of the observed values.
> On Jul 5, 2019, at 6:42 AM, Slawomir Pryczek <slawek1...@gmail.com> wrote: > > Sure it has a race issue, because in this example you're mixing atomic > operations with mutex, when you want your code to be thread safe you need to > do access to the variable using mutex or using atomic in all cases. Because > both ways work differently and are not "interchargable" so you can't cover > access to same object using a mix of 2 ways. > > You can fix your code like this: > 1a. change m.RLock() to m.Lock()/m.Unlock() near atomic.AddInt32(&n, 1) > because it's writing operation so you need write mutex > 1b. add m.Lock()/m.Unlock near n=0 because it's writing operation as well > The, you can remove atomic ops, because now all the code is covered by mutexes > > 2. Change n=0 to atomic.StoreInt32(&n, 0) > Then you can remove all mutexes, because access is covered by atomic ops > > > > > > W dniu piątek, 5 lipca 2019 12:40:32 UTC+2 użytkownik White Pure napisał: >> >> 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/ed3e8643-8781-438d-8191-1c60ee7473c5%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- 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/13E1DA75-C9A5-4D7F-8FAA-EC1A4DF24061%40ix.netcom.com. For more options, visit https://groups.google.com/d/optout.