Skip to content
Related Articles

Related Articles

Improve Article
How to Fix Race Condition using Atomic Functions in Golang?
  • Last Updated : 19 May, 2020

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :