atomic.LoadUint32() Function in Golang With Examples
Last Updated :
01 Apr, 2020
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The LoadUint32() function in Go language is used to atomically load *addr. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func LoadUint32(addr *uint32) (val uint32)
Here, addr indicates address.
Note: (*uint32) is the pointer to a uint32 value. However, uint32 contains the set of all unsigned 32-bit integers from 0 to 4294967295.
Return value: It returns the value loaded to the *addr.
Example 1:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i uint32 = 57
j uint32 = 0
k uint32 = 444
l uint32 = 45646667
)
load_1 := atomic.LoadUint32(&i)
load_2 := atomic.LoadUint32(&j)
load_3 := atomic.LoadUint32(&k)
load_4 := atomic.LoadUint32(&l)
fmt.Println(load_1)
fmt.Println(load_2)
fmt.Println(load_3)
fmt.Println(load_4)
}
|
Output:
57
0
444
45646667
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var u uint32
for i := 3; i < 315; i++ {
go func() {
atomic.AddUint32(&u, 2)
}()
}
fmt.Println(atomic.LoadUint32(&u))
}
|
Output:
498 // A random value is returned in each run
In the above example, the new values are returned from AddUint32() method in each call until the loop stops, LoadUint32() method loads these new uint32 values. And these values are stored in different addresses which can be random one so, the output of the LoadUint32() method here in each run is different. So, here a random value is returned in the output.
Share your thoughts in the comments
Please Login to comment...