Atomic Variable in Golang
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.
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.
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.