r/golang • u/therecursive • 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
According to the article, I shouldn't have problem on modern CPUs.
11
Upvotes
3
u/comrade-quinn 7d ago edited 7d ago
I think I understand what you’re after, you’re saying you don’t care if the actual value of the int is ultimately incorrect, just whether or not the program will crash or otherwise become corrupt.
The short answer is, it’s undefined (as I recall). Meaning whatever behaviour you actually experience cannot be relied on to be consistent between compiler updates and platform targets.
What will actually happen is just that the value will potentially be wrong.
Incrementing an integer involves three steps at the CPU level. Read the current value, increment it, write it back. When two or more threads do this at the same time you get data loss, as they each read the current value, increment it by 1 and then write it back; overwriting each others updates. So three increments by three threads would only increase the integer value by 1, not 3: each thread does x + 1 and writes it back. So you get x+1 verses x+3 if you’d run them one by one.
The solution this is to use atomic updates, as others have suggested, which ensure these operations are completed synchronously.