Open In App

atomic.LoadInt64() Function in Golang With Examples

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 LoadInt64() 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 LoadInt64(addr *int64) (val int64)

Here, addr indicates address.

Note: (*int64) is the pointer to a int64 value. However, int64 contains the set of all signed 64 bit integers from -9223372036854775808 to 9223372036854775807.

Return value: It returns the value loaded to the addr.

Example 1:




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


Output:

68678677
-45369087334
0
75

Example 2:




// Program to illustrate the usage of
// LoadInt64 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 int64
  
    // For loop
    for i := 2; i < 500; i += 3 {
  
        // Function with AddInt64 method
        go func() {
            atomic.AddInt64(&x, 5)
        }()
    }
  
    // Prints loaded values address
    fmt.Println(atomic.LoadInt64(&x))
}


Output:

435   // A random value is returned in each run

In the above example, the new values returned from AddInt64() method in each call until the loop stops are stored in different addresses, LoadInt64() method returns the address of these new values. And this address can be random one so, the output of the LoadInt64() method in each run is different. So, here a random value is returned in the output.



Last Updated : 01 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads