Hi,
    Thanks for your reply.
    The second bug is a known issue, so let’s ignore that. In that case, I 
think function f still can only be executed once.
    But why does the load and store of o.done need to be done using atomic 
operations? I suppose there’s mutex assuring the happens-before.

在 2019年5月7日星期二 UTC+8下午9:33:41,Robert Johnstone写道:
>
> 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/8317e218-c04f-432f-a635-2d72ac160acc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to