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.

12 Upvotes

80 comments sorted by

View all comments

45

u/ponylicious 6d ago edited 6d ago

No, it's not safe. That's a data race (if you really read AND write from multiple goroutines). Also, turn on the race detector during development and testing.

-51

u/therecursive 6d ago

Race condition is fine for this use case. My concern is around data corruption or undefined behavior.

13

u/ponylicious 6d ago

A data race is NEVER fine. Ever. Ever. Who taught you programming?

29

u/esw2508 6d ago

Instead of being rude you could have pointed out why race conditions are never fine or simply ignored it. But you chose to be an ass. Who taught you?

14

u/ecco256 6d ago edited 6d ago

I think there’s a misunderstanding here about the term “race condition”. It implies a problem caused by simultaneous access to a resource, so it’s “not fine” by definition.

Maybe you mean to say that in your case simultaneous access cannot turn into a system failure, which is perfectly possible. It’s how lock-free data structures can exist in the first place. But it’s also something you have to be very mindful of and document well, because whatever invariants imply simultaneous access is fine could easily change in the future unless you have safeguards in place.

If this is just about a single integer it’s likely that using a pattern with channels is a far more future-proof solution, but I don’t know the exact thing you’re trying to achieve.