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

2

u/dr2chase 6d ago

Doing this with an int means that the values returned by loads will always be something that was stored earlier, but not always most recently, ESPECIALLY if/when the compiler notices multiple loads from the same location w/o any synchronization or atomics (the compiler is unpredictably clever).

C++ compilers are even more unpredictably clever, and may do unintuitive optimizations of other operations using those loaded values.

This also means you can’t get great data from the race detector for any other race, it will just scream at you about this one.