atomic.LoadInt32() 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 LoadInt32() function in Go language is used to atomically loads *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 LoadInt32(addr *int32) (val int32)
Here, addr indicates address.
Note: (*int32) is the pointer to a int32 value. However, int32 contains the set of all signed 32-bit integers from -2147483648 to 2147483647.
Return Value: It returns the value loaded to the addr.
Example 1:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i int32 = 57567
j int32 = -842
k int32 = 17
l int32 = 3455
)
load_1 := atomic.LoadInt32(&i)
load_2 := atomic.LoadInt32(&j)
load_3 := atomic.LoadInt32(&k)
load_4 := atomic.LoadInt32(&l)
fmt.Println(load_1)
fmt.Println(load_2)
fmt.Println(load_3)
fmt.Println(load_4)
}
|
Output:
57567
-842
17
3455
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var x int32
for i := 1; i < 789; i += 2 {
go func() {
atomic.AddInt32(&x, 4)
}()
}
fmt.Println(atomic.LoadInt32(&x))
}
|
Output:
1416 // A random value is returned in each run
In the above example, the new values are returned from AddInt32() method in each call until the loop stops, LoadInt32() method loads these new int32 values. And these values are stored in different addresses which can be random one so, the output of the LoadInt32() method here in each run is different. So, here a random value is returned in the output.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...