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.
Example:
package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
)
var (
c int32
waitgroup sync.WaitGroup
)
func main() {
waitgroup.Add(3)
go increment( "geeks" )
go increment( "for" )
go increment( "geeks" )
waitgroup.Wait()
fmt.Println( "Counter:" , c)
}
func increment(name string) {
defer waitgroup.Done()
for range name {
atomic.AddInt32(&c, 1)
runtime.Gosched()
}
}
|
Output:
Counter: 13
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.
Last Updated :
19 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...