Open In App

atomic.LoadInt32() Function in Golang With Examples

Last Updated : 01 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:




// Program to illustrate the usage of
// LoadInt32 function in Golang
  
// Including main package
package main
  
// importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Assigning values to the int32
    var (
        i int32 = 57567
        j int32 = -842
        k int32 = 17
        l int32 = 3455
    )
  
    // Calling LoadInt32 method
    // with its parameters
    load_1 := atomic.LoadInt32(&i)
    load_2 := atomic.LoadInt32(&j)
    load_3 := atomic.LoadInt32(&k)
    load_4 := atomic.LoadInt32(&l)
  
    // Displays the int32 value 
    // loaded in the *addr
    fmt.Println(load_1)
    fmt.Println(load_2)
    fmt.Println(load_3)
    fmt.Println(load_4)
}


Output:

57567
-842
17
3455

Example 2:




// Program to illustrate the usage of
// LoadInt32 function in Golang
  
// Including main package
package main
  
// Importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Declaring x
    var x int32
  
    // For loop
    for i := 1; i < 789; i += 2 {
  
        // Function with AddInt32 method
        go func() {
            atomic.AddInt32(&x, 4)
        }()
    }
  
    // Prints loaded values address
    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
Previous
Next
Share your thoughts in the comments

Similar Reads