Open In App

How to Fix Race Condition using Atomic Functions in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

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:




// Golang program to fix the race
// condition using atomic package
package main
  
import (
    "fmt"
    "runtime"
    "sync"
    "sync/atomic"
)
  
// All goroutines will increment  variable c
// waitgroup is waiting for the completion
// of program.
var (
    c         int32
    waitgroup sync.WaitGroup
)
  
func main() {
  
    // with the help of Add() function add
    // one for each goroutine
    // a count of total 3
    waitgroup.Add(3)
  
    // increment with the help
    // of increment() function
    go increment("geeks")
    go increment("for")
    go increment("geeks")
  
    // waiting for completion
    // of goroutines.
    waitgroup.Wait()
  
    // print the counter
    fmt.Println("Counter:", c)
  
}
  
func increment(name string) {
  
    // Done() function used
    // to tell that it is done.
    defer waitgroup.Done()
  
    for range name {
  
        // Atomic Functions
        // for fix race condition
        atomic.AddInt32(&c, 1)
  
        // enter thread in the line by line
        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
Previous
Next
Share your thoughts in the comments
Similar Reads