atomic.SwapInt64() 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 SwapInt64() function in Go language is used to atomically store new value into *addr and returns the previous *addr value. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func SwapInt64(addr *int64, new int64) (old int64)
Here, addr indicates address. And new is the new int64 value and old is the older int64 value.
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 stores the new int64 value into the *addr and returns the previous *addr value.
Example 1:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var x int64 = 25786808555
var old_val = atomic.SwapInt64(&x, 4567898196323)
fmt.Println( "Stored new value: " ,
x, ", Old value: " , old_val)
}
|
Output:
Stored new value: 4567898196323, Old value: 25786808555
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var m int64 = 78453984556
var n int64 = 364576677888
var oldVal1 = atomic.SwapInt64(&m, 78453984556)
var oldVal2 = atomic.SwapInt64(&n, 935128383)
fmt.Println((oldVal1) == m)
fmt.Println((oldVal2) == n)
}
|
Output:
true
false
Here, the oldVal1 is equal to “m” as the new value to be stored in the *addr is same as the old value so true is returned but oldVal2 is not equal to “n” as there the old value is not similar to the newly assigned value hence, false is returned.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...