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:
package main
import (
"fmt"
"math/rand"
"sync"
"sync/atomic"
"time"
)
var waittime sync.WaitGroup
var atmvar int32
func hike(S string) {
for i := 1; i < 7; i++ {
time .Sleep( time .Duration(( rand .Intn(5))) * time .Millisecond)
atomic.AddInt32(&atmvar, 1)
fmt.Println(S, i, "count ->" , atmvar)
}
waittime.Done()
}
func main() {
waittime.Add(2)
go hike( "cat: " )
go hike( "dog: " )
waittime.Wait()
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:
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var atmvar uint32
var wait sync.WaitGroup
for i := 0; i < 30; i += 2 {
wait.Add(1)
go func() {
atomic.AddUint32(&atmvar, 2)
wait.Done()
}()
}
wait.Wait()
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.