Why do we need separate functions for atomic memory operations? If we write to a variable whose size is less or equal to the machine word size (which is what the
int type is defined to be), such as
a=1, wouldn’t that be atomic? The Go memory model actually guarantees that the write operation will be atomic; however, it does not guarantee when other goroutines will see the effects of that write operation, if ever. Let’s try to dissect what this statement means. The first part simply says that if you write to a shared memory location that is the same size as a machine word (i.e.,
int) from one goroutine and read it from another, you will not observe some random value even if there is a race. The memory model guarantees that you will only observe the value before the write operation, or the value after it (this is not true for all languages.) This also means that if the write operation is larger than the machine word size, then a goroutine reading this...