Open In App

atomic.LoadUint32() 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 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:




// Program to illustrate the usage of
// LoadUint32 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 uint32
    var (
        i uint32 = 57
        j uint32 = 0
        k uint32 = 444
        l uint32 = 45646667
    )
  
    // Calling LoadUint32 method 
    // with its parameters
    load_1 := atomic.LoadUint32(&i)
    load_2 := atomic.LoadUint32(&j)
    load_3 := atomic.LoadUint32(&k)
    load_4 := atomic.LoadUint32(&l)
  
    // Displays the uint32 value
    // loaded in the *addr
    fmt.Println(load_1)
    fmt.Println(load_2)
    fmt.Println(load_3)
    fmt.Println(load_4)
}


Output:

57
0
444
45646667

Example 2:




// Program to illustrate the usage of
// LoadUint32 function in Golang
  
// Including main package
package main
  
// Importing fmt and sync/atomic
import (
    "fmt"
    "sync/atomic"
)
  
// Main function
func main() {
  
    // Declaring u
    var u uint32
  
    // For loop
    for i := 3; i < 315; i++ {
  
        // Function with AddUint32 method
        go func() {
            atomic.AddUint32(&u, 2)
        }()
    }
  
    // Prints loaded values address
    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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads