-4

a pointer value has the length of one machine word, so read/write operations should naturally be atomic. Can we just use pointer to a struct and concurrently access it as long as we don't change the thing the pointer points at?

type A struct{
    x int
    y int
    z int
}
var v *A
func main(){
    v = &A{}
    go func(){
        u := v
        fmt.Print(u.x)
        fmt.Print(u.y)
        fmt.Print(u.z)
        //will it only print 000 or 111?
    }()
    go func(){
        u := &A{x:1, y:1, z:1}
        v = u
    }()
}
lotsof one
  • 55
  • 4

1 Answers1

2

a pointer value has the length of one machine word

True

so read/write operations should naturally be atomic

False

Can we just use pointer to a struct and concurrently access it as long as we don't change the thing the pointer points at?

(Btw: Your example code contains a data race and this is undefined.)

No.

The 80s and their 8 or 16 bit microcontrollers are longe gone. Just because something has the size of a machine word doesn't make its reads/write atomic at all.

To answer your question "why should we use atomic.LoadPointer?": You should use it always if you want to load a pointer atomically without other syncronisation.

Volker
  • 36,165
  • 6
  • 76
  • 80