In Go language, Atomic Variables are utilized in order to control state. Here, the “sync/atomic” package must be used to use these variables. Moreover, it also prevents race conditions which allows two or more Goroutines to access identical sources. The Atomic counters are available for several goroutines. The main means for managing states in go language is communication over channels.
Example 1:
// Golang program to illustrate the usage of // atomic variable // Including main package package main // Importing sync/atomic, math/rand, // fmt, sync, and time import ( "fmt"
"math/rand"
"sync"
"sync/atomic"
"time"
) // Using sync.WaitGroup in order to // wait for a collection of // goroutines to finish var waittime sync.WaitGroup // Declaring atomic variable var atmvar int32 // Defining increment function func hike(S string) { // For loop
for i := 1; i < 7; i++ {
// Calling sleep method with its duration
// and also calling rand.Intn method
time .Sleep( time .Duration(( rand .Intn(5))) * time .Millisecond)
// Calling AddInt32 method with its
// parameter
atomic.AddInt32(&atmvar, 1)
// Prints output
fmt.Println(S, i, "count ->" , atmvar)
}
// Wait completed
waittime.Done()
} // Main function func main() { // Calling Add method w.r.to
// waittime variable
waittime.Add(2)
// Calling hike method with
// values
go hike( "cat: " )
go hike( "dog: " )
// Calling wait method
waittime.Wait()
// Prints the value of last count
fmt.Println( "The value of last count is :" , atmvar)
} |
Output:
dog: 1 count -> 1 cat: 1 count -> 2 dog: 2 count -> 3 dog: 3 count -> 4 cat: 2 count -> 5 cat: 3 count -> 6 cat: 4 count -> 7 cat: 5 count -> 8 cat: 6 count -> 9 dog: 4 count -> 10 dog: 5 count -> 11 dog: 6 count -> 12 The value of last count is : 12
In the above method, the atomic variable is of type int32. Here, rand.Intn() method is used to print random integer until the loop stops. After that, AddInt32 method is used which adds the atomic variable with another int32 number and then returns it in the count.
Example 2:
// Golang program to illustrate the usage of // AfterFunc() function // Including main package package main // Importing sync/atomic, fmt, // and sync import ( "fmt"
"sync"
"sync/atomic"
) // Calling main func main() { // Declaring atomic variable
var atmvar uint32
// Using sync.WaitGroup in order to
// wait for a collection of
// goroutines to finish
var wait sync.WaitGroup
// For loop
for i := 0; i < 30; i += 2 {
// Calling Add method
wait.Add(1)
// Calling AddUint32 method under
// go function
go func() {
atomic.AddUint32(&atmvar, 2)
// Wait completed
wait.Done()
}()
}
// Calling wait method
wait.Wait()
// Prints atomic variables value
fmt.Println( "atmvar:" , atmvar)
} |
Output:
atmvar: 30
In the above method, the atomic variable is of type uint32. Here, AddUint32() method is used under the for loop which adds its parameters until loop stops and then returns the value of the atomic variable.