atomic.AddInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt64() function in Go language is used to automatically add delta to the *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 AddInt64(addr *int64, delta int64) (new int64)
Here, addr indicates address and delta indicates a small number of bits greater than zero.
Note: (*int64) is the pointer to a int64 value. Moreover, int64 contains the set of all signed 64-bit integers from -9223372036854775808 to 9223372036854775807.
Return Value: It adds addr and delta automatically and returns a new value.
Example 1:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
s int64 = 67656
t int64 = 90
u int64 = 922337203685477580
v int64 = -9223372036854775807
)
const (
w int64 = 5
x int64 = 8
)
output_1 := atomic.AddInt64(&s, w)
output_2 := atomic.AddInt64(&t, x-w)
output_3 := atomic.AddInt64(&u, x-6)
output_4 := atomic.AddInt64(&v, -x)
fmt.Println(output_1)
fmt.Println(output_2)
fmt.Println(output_3)
fmt.Println(output_4)
}
|
Output:
67661
93
922337203685477582
9223372036854775801
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
type addr int64
func (s *addr) adds() int64 {
return atomic.AddInt64((*int64)(s), 9)
}
func main() {
var s addr
for i := 1; i < 10000; i *= 5 {
fmt.Println(s.adds())
}
}
|
Output:
9
18
27
36
45
54
In the above example, we have defined a function adds that returns the output returned from calling AddInt64 method. In the main function, we have defined a “for” loop that will increment the value of ‘s’ in each call. Here, the second parameter of the AddInt64() method is constant and only the value of the first parameter is variable. However, the output of the previous call will be the value of the first parameter of the AddInt64() method in the next call until the loop stops.
Lets see how above example works:
1st parameter = 0, 2nd parameter = 9 // returns (0 + 9 = 9)
// Now, the above output is 1st parameter in next call to AddInt64() method
1st parameter = 9, 2nd parameter = 9 // returns (9 + 9 = 18)
1st parameter = 18, 2nd parameter = 9 // returns (18 + 9 = 27) and so on.
Last Updated :
31 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...