```go
package main
import (
"fmt"
"time"
)
func main() {
var num = 10
var p = &num
c := make(chan int)
go func() {
time.Sleep(time.Second)
c <- *p //-----> 11
//c <- num //----->10
}()
time.Sleep(2 * time.Second)
num++
fmt.Println(<-c)
fmt.Println(p)
return
}
```
为什么 *p 和num的结果不一样
我在golang-nuts上问了这个问题,下面是一些回复:
1.
You have a data race, what value you get from dereferencing p is
undefined, it could be 10, it could be 11, it could wipe your
harddrive or launch the missiles.
2.
The program is really racy, but the result is also really some counter-intuitive.
The following program also print 10, which means evaluation of pointer dereference
is some different to evaluation of other expressions in flow.
package main
import (
"fmt"
"time"
)
func main() {
var num = 10
var p = &num
c := make(chan int)
go func() {
c <- func()int{return *p}() // with this line we will get 10 from channel c
//c <- *p * 1 // with this line we will get 10 from channel c
//c <- *p // with this line we will get 11 from channel c
//c <- num // with this line we will get 10 from channel c
}()
time.Sleep(time.Second)
num++
fmt.Println(<-c)
fmt.Println(p)
}
IMO, I think this is a bug.
I mean it can be viewed as a bug for inconsistency.
But from the memory model view, it can also not be viewed as a bug.
#20
更多评论