Sitemap
The Ordinary Programmer

The Ordinary Programmer is for coders who embrace simplicity and practicality. We share real-world tips, project stories, and tech insights for developers at every level. You don’t need to be a superstar — just a programmer who loves to learn and build helpful software.

Member-only story

Decrypt Go: Atomic Package Addressing Concurrency Issues

4 min readMar 6, 2024

--

Press enter or click to view image in full size
dalle-3 Generation

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…

--

--

The Ordinary Programmer
The Ordinary Programmer

Published in The Ordinary Programmer

The Ordinary Programmer is for coders who embrace simplicity and practicality. We share real-world tips, project stories, and tech insights for developers at every level. You don’t need to be a superstar — just a programmer who loves to learn and build helpful software.

huizhou92
huizhou92

Written by huizhou92

Golang backend engineer. Specializes in cloud, data, and security. Lifelong learner. Efficiency enthusiast.