Normal should be constant output
test1
test2
........
But only test1 output, the program hung up, there is no response The assignment of the pointer is the most basic operation, this should be thread-safe to meet the period But this test has not been able to
type Point struct {
X int
Y int
}
func main() {
var p *Point = nil
test := true
go func() {
for test {
if tmp := p; tmp == nil {
p = &Point{}
}
}
}()
go func() {
for test {
if tmp := p; tmp != nil {
p = nil
}
}
}()
n := 0
for test {
n++
fmt.Printf("testing%v....\r\n",n)
time.Sleep(1000 * time.Millisecond)
}
fmt.Printf("test fail")
}
code: https://play.golang.org/p/-NTq-2iyX5W
if change pointer to int, this is good
func main() {
var p int = 0
test := true
go func() {
for test {
if tmp := p; tmp == 0 {
p = 1
}
}
}()
go func() {
for test {
if tmp := p; tmp != 0 {
p = 0
}
}
}()
n := 0
for test {
n++
fmt.Printf("testing%v....\r\n",n)
time.Sleep(1000 * time.Millisecond)
}
fmt.Printf("test fail")
}