Member-only story
Decrypt Go: Atomic Package Addressing Concurrency Issues
atomic is the basis for concurrency
Note: Non-members can read the full story in this link.
Cache Consistency Issues
In concurrent programming, it’s common to encounter issues like this. For instance, when two goroutines simultaneously read and write to a variable, concurrency issues arise. Take, for example, the following code: example
func main() {
var a int
count := 1000000
wg := sync.WaitGroup{}
for i := 0; i < 5; i++ {
wg.Add(1)
go func(wg *sync.WaitGroup) {
for i := 0; i < count; i++ {
a++
}
wg.Done()
}(&wg)
}
wg.Wait()
fmt.Println(a)
}I don’t know what the result of this code is, but it’s highly likely not the desired 5000000. It’s very likely to be a number much smaller than 5000000. Why does this happen?
In computer architecture, multi-core processors often have multiple levels of cache, with each core having its cache. These caches store recently used data to speed up access to the data.
When a thread writes to a variable, it first loads a copy of the variable from memory into its cache and makes modifications. Then, the thread writes the modified value back to memory.
During this process, other…

