How to Fix Race Condition using Atomic Functions in Golang?
Two or more processes executing in a system with an illusion of concurrency and accessing shared data may try to change the shared data at the same time. This condition in the system is known as a race condition. To see the sample code for Race Condition in Golang, you can refer to this article.
Atomic package in Golang provides the low-level locking mechanisms for synchronizing access to pointers and integers etc. The atomic/sync package functions are used to fix the race condition.
Here, you can see we are using atomic.AddInt32() function to synchronize the addition of the integer values so that only one goroutine is allowed to complete the add operation at a time. Remember one thing, always check the output of such a program using the online compiler as you might get the same output every time(means no race condition) due to the deterministic nature. So use the local compiler like Visual Studio or CMD to see the results.