3 ms·
With the exception of goroutine memory/stack usage perhaps, these are not implementation details - they are core parts of the semantics of the language (especia
by simiones 6y ago
With the exception of goroutine memory/stack usage perhaps, these are not implementation details - they are core parts of the semantics of the language (especially since asynchronicity is a fundamental aspect of the language through goroutines).
For example, is this piece of code correct?
x := 7
go func() {
if x == 7 {
fmt.Println("x = 7")
} else {
fmt.Println("x != 7")
}
}()
x = 8
What are its possible valid outputs? (for the record, as far as I know this is incorrect code in Go, as atomic access is not guaranteed for any variable, so not only could this print any of the two outputs, it could also observe invalid values for x)
What about this code:
x := 7
c := make(chan struct{}, 0)
go func() {
if x == 7 {
fmt.Println("x = 7")
} else {
fmt.Println("x != 7")
}
c<-struct{}{}
}()
<-c
x = 8
Can you tell from the language spec whether this code is safe, and what it's output will be? (~~it's not safe, as far as I know~~ reading the memory model[0], I believe it is safe).
[0] https://golang.org/ref/mem https://golang.org/ref/mem
- erik_seaberg 6y agoTo be fair, Java’s memory model was also pretty broken for several years.