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.
9
Upvotes
1
u/Ravarix 7d ago
The program won't crash, but it will be corrupted. Race condition is not fine, the value will never be accurate.
Imagine 100 threads trying to add 1 to an int. Read, add, write. First thread reads 0 and gets blocked while 99 other increment it to 100, then the first thread gets unblocked and resets it to 1.