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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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()
    }
}

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.