atomic.AddUint64() Function in Golang With Examples
Last Updated :
17 Jan, 2022
In Go language, atomic packages supply lower level atomic memory that is helpful is implementing synchronization algorithms. The AddUint64() 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 AddUint64(addr *uint64, delta uint64) (new uint64)
Here, addr indicates address and delta indicates a small number of bits greater than zero. Moreover, if you want to subtract a signed positive constant value c from x, then you can do it by AddUint64(&x, ^uint64(c-1)). And if you want to decrement x particularly, then it can be done by AddUint64(&x, ^uint64(0)).
Note: (*uint64) is the pointer to a uint64 value. Moreover, uint64 contains the set of all unsigned 64-bit integers from 0 to 18446744073709551615.
Return Value: It adds addr and delta automatically and returns a new value.
Example 1:
C
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i uint64 = 453
j uint64 = 167
k uint64 = 18446744073709551615
l uint64 = 0
z int = 15
)
const (
x uint64 = 7
y uint64 = 12
)
a_1 := atomic.AddUint64(&i, -uint64(z))
a_2 := atomic.AddUint64(&j, ^(y - 1))
a_3 := atomic.AddUint64(&k, x-1)
a_4 := atomic.AddUint64(&l, ^uint64(z-1))
fmt.Println(a_1)
fmt.Println(a_2)
fmt.Println(a_3)
fmt.Println(a_4)
}
|
Output:
438
155
5
18446744073709551601
Example 2:
C
package main
import (
"fmt"
"sync/atomic"
)
type addr uint64
func (u *addr) adds() uint64 {
return atomic.AddUint64((*uint64)(u), 325)
}
func main() {
var u addr
for i := 1; i < 11; i *= 3 {
fmt.Println(u.adds())
}
}
|
Output:
325
650
975
In the above example, we have defined a function adds that returns the output returned from calling AddUint64 method. In the main function, we have defined a “for” loop that will increment the value of ‘u’ in each call. Here, the second parameter of the AddUint64() 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 AddUint64() method in the next call until the loop stops.
Lets see how above example works:
1st parameter = 0, 2nd parameter = 325 // returns (0 + 325 = 325)
// Now, the above output is 1st parameter in next call to AddUint64() method
1st parameter = 325, 2nd parameter = 325 // returns (325 + 325 = 650)
1st parameter = 650, 2nd parameter = 325 // returns (650 + 325 = 975)
Share your thoughts in the comments
Please Login to comment...