Back to the primary question: Is it safe to read condition if I add a break
to the loop like this?
var condition bool
var wg sync.WaitGroup
for _, item := range items {
if true {
break
}
wg.Add(1)
go func(item) {
if meetsCondition(item) {
condition = true
}
wg.Done()
}(item)
}
wg.Wait()
// is it safe to check condition here?
There is not even one mention of WaitGroup in the spec and it's
documentation is saying Wait: "Wait blocks until the WaitGroup counter is
zero." which does
not set any happens-before relationship (or does it?). Does it mean that
the first answer "It is safe to check condition after wg.Wait returns" is
unofficial? If it's official what are the reasons for it I am missing?
Thanks alot if you answer.
Dne středa 7. května 2014 7:45:43 UTC+2 Dmitry Vyukov napsal(a):
>
> wg.Add happens-before wg.Wait
>
> You need to protect accesses to condition.
> Either change it to uint32 and use atomic.StoreUint32 or aggregate
> results with a channel:
>
> done := make(chan bool)
> for _, item := range items {
> go func(item) {
> done <- meetsCondition(item)
> }(item)
> }
> cond := false
> for _ := range items {
> cond = cond | <-done
> }
>
>
>
> On Tue, May 6, 2014 at 5:55 PM, <[email protected] <javascript:>> wrote:
> > Here is some example code that demonstrates my question:
> >
> > var condition bool
> > var wg sync.WaitGroup
> > for _, item := range items {
> > wg.Add(1)
> > go func(item) {
> > if meetsCondition(item) {
> > condition = true
> > }
> > wg.Done()
> > }(item)
> > }
> > wg.Wait()
> > // is it safe to check condition here?
> >
> > Does wg.Wait() act as a memory barrier so that it's safe to check
> condition?
> > If not, what's the best way to represent this idiom?
> (atomic.Load/Store?)
> > Thanks!
> >
> > --
> > 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] <javascript:>.
> > 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 [email protected].
For more options, visit https://groups.google.com/d/optout.