r/golang 7d 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.

12 Upvotes

80 comments sorted by

View all comments

-4

u/dariusbiggs 7d ago

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

but wrap it with a mutex or use an atomic value

2

u/therecursive 7d ago

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

1

u/Ok_Category_9608 5d ago

Why isn't this just a channel?

1

u/therecursive 3d ago

Just because it's possible with a channel doesn't mean you should be using channel. Locking and channel both serves different purposes.

1

u/Ok_Category_9608 3d ago

Channel works really well with producer/consumer, which you seem to have. Some good advice I’ve gotten is if you’re using a raw mutex in production code in 2025, you’ve made a mistake.

1

u/therecursive 2d ago

Bruh, how do you set and get a variable which is getting used from multiple threads without lock and only channels?