Yes. 1. `counter++` happens-before `ch <- struct{}{}`, because in a single goroutine, happens-before is equivalent with lexical statement order 2. `ch <- struct{}{}` happens-before `<-ch` completes, because "A send on a channel happens before the corresponding receive from that channel completes". 3. `<-ch` completion happens-before `fmt.Println(counter)`, again because in a single goroutine, happens-before is equivalent with lexical statement order
Therefore, `counter++` happens-before `fmt.Println(counter)`. On Mon, Feb 1, 2021 at 4:06 PM xie cui <cuiwei...@gmail.com> wrote: > here is the code: > package main > > import "fmt" > > func main() { > counter := 0 > ch := make(chan struct{}, 1) > closeCh := make(chan struct{}) > go func() { > counter++ //(1) > ch <- struct{}{} > }() > go func() { > _ = <-ch > fmt.Println(counter) //(2) > close(closeCh) > }() > _ =<-closeCh > } > > is (1) happens before (2)? why? > > -- > 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/5b0143e2-196e-4d73-a3e4-58a84339f433n%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/5b0143e2-196e-4d73-a3e4-58a84339f433n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- 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/CAEkBMfG-8tCCZn8N_Q%3D%3DHb7OZuAGb2AfE2Tg9piztVdhLAi1vA%40mail.gmail.com.