golang memory model?

81 views
Skip to first unread message

xie cui

unread,
Feb 1, 2021, 10:05:36 AM2/1/21
to golang-nuts
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?

Axel Wagner

unread,
Feb 1, 2021, 10:26:47 AM2/1/21
to xie cui, golang-nuts
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)`.

--
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...@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.

Shulhan

unread,
Feb 1, 2021, 10:33:01 AM2/1/21
to xie cui, golang-nuts
I believe the answer is not g. https://golang.org/ref/mem#tmp_7
Reply all
Reply to author
Forward
0 new messages