Hello, The code contains two bugs.
1) The load and store of o.done needs to be done using atomic stores. 2) The statement to set o.done = 1 needs to be after the call to f. Otherwise, another goroutine can hit the check at the top of Done and return before the code in f has completed. On Tuesday, 7 May 2019 08:55:06 UTC-4, wu.pu...@gmail.com wrote: > > Hi, > I did a quiz recently, but I'm having problem with the answer. > Quiz: https://github.com/smallnest/go-concurrent-quiz#-quiz-4 > > > package doublecheck > > import ( > "sync" > ) > > type Once struct { > m sync.Mutex > done uint32 > } > > func (o *Once) Do(f func()) { > if o.done == 1 { > return > } > > o.m.Lock() > defer o.m.Unlock() > if o.done == 0 { > o.done = 1 > f() > } > } > > Question > > - A: can't compile > - B: can run that implemented the singleton pattern correctly > - C: can run but has not implemented the singleton pattern, function > f may run multi times. > - D: programms will be panic when use this Once concurrently. > > Some other people and I think the answer is B, but the author says the > answer is C. > > We think this implements happen-before, but the author doesn't think so. > > Can anyone help to explain this? > > Thanks! > <https://github.com/smallnest/go-concurrent-quiz#-quiz-5> > -- 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/fb603a1b-4737-45bf-8646-4915466047c4%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.