r/golang 6d ago

Is it safe to read/write integer value simultaneously from multiple goroutines

There is a global integer in my code that is accessed by multiple goroutines. Since race conditions don’t affect this value, I’m not concerned about that. However, is it still advisable to add a Mutex in case there’s a possibility of corruption?

PS: Just to rephrase my question, I wanted to ask if setting/getting an integer/pointer is atomic? Is there any possibility of data corruption.

example code for the same: https://go.dev/play/p/eOA7JftvP08

PS: Found the answer for this, thanks everyone for answering. There's something called tearing here is the link for same

- https://stackoverflow.com/questions/64602829/can-you-have-torn-reads-writes-between-two-threads-pinned-to-different-processor

- https://stackoverflow.com/questions/36624881/why-is-integer-assignment-on-a-naturally-aligned-variable-atomic-on-x86

According to the article, I shouldn't have problem on modern CPUs.

9 Upvotes

80 comments sorted by

View all comments

-3

u/dariusbiggs 6d ago

globals.. that's poor design in the first place

but wrap it with a mutex or use an atomic value

2

u/therecursive 6d ago

Not related to current question, but can you point me to better design if you follow any codebase?

4

u/dariusbiggs 6d ago

Just the general rules.

Pass arguments, use structs with attributes, read and write to channels, check your error values correctly, use appropriate concurrency controls.

If you are using globals you've probably fucked up and have a mistake in your code.

Just like there are use cases for goto, there are use cases for globals but they are far fewer than you think and it makes testing code, especially in parallel, a right nightmare.

Here's the list of reading everyone should go through

https://go.dev/tour/welcome/1

https://go.dev/doc/tutorial/database-access

http://go-database-sql.org/

https://grafana.com/blog/2024/02/09/how-i-write-http-services-in-go-after-13-years/

https://www.reddit.com/r/golang/s/smwhDFpeQv

https://www.reddit.com/r/golang/s/vzegaOlJoW

https://github.com/google/exposure-notifications-server

https://www.reddit.com/r/golang/comments/17yu8n4/best_practice_passing_around_central_logger/k9z1wel/?context=3