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, [email protected] 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 [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/538cead0-696a-4272-a9c6-e9b9f4f55c43%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.