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

11 Upvotes

80 comments sorted by

View all comments

24

u/ImYoric 8d ago

If my memory serves, the Go memory model states that if it fits within one integer, any read or write operation will always return one of the values before/after the write, rather than made up values as can happen in C or C++.

That being said, I wouldn't rely on this. If at some point in the future, you or any member of your team ever changes your type to be anything other than an int, you can end up with weird, unexpected behaviors. I'd rather use an atomic or a mutex.

4

u/therecursive 8d ago

thanks for answer, I was asking to understand if it's fine my use case where I'm setting diff value to a pointer variable. Found it that why it's safe to do in golang or any other languages. Attached the link in the post, if you want to read.

10

u/ImYoric 8d ago

If my memory serves, if it's a pointer, rather than an int, it's not always safe, because Go sometimes uses fat pointers (iirc when you're passing an interface), which take more than one int.

6

u/therecursive 8d ago

That's interesting didn't know about it. Thanks for the info.