-3

In program languages that support multi-thread, we are always taught to use atomic operations or locks or channels to synchronize multiple threads when they read/write a variable at the same time.

My question is, if the variable's byte length is not greater than the machine word length, can the CPU execute it atomically? And if so, can we simply write concurrent access code in high level language?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
lotsof one
  • 77
  • 5

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
  • 40,468
  • 7
  • 81
  • 87