atomic.AddUintptr() Function in Golang With Examples
Last Updated :
31 Jan, 2022
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddUintptr() 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 AddUintptr(addr *uintptr, delta uintptr) (new uintptr)
Here, addr indicates address and delta indicates a small number of bits greater than zero.
Note: (*uintptr) is the pointer to a uintptr value. And uintptr is an integer type that is large enough and can hold the bit pattern of any pointer.
Return value: It adds addr and delta automatically and returns a new value.
Example 1:
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
w uintptr = 0
x uintptr = 255
y uintptr = 564688
z uintptr = 656757686877
)
const (
m uintptr = 78
n uintptr = 96
)
p_1 := atomic.AddUintptr(&x, (m))
p_2 := atomic.AddUintptr(&y, ^(n - 1))
p_3 := atomic.AddUintptr(&z, (2))
p_4 := atomic.AddUintptr(&w, (n - m))
fmt.Println(p_1)
fmt.Println(p_2)
fmt.Println(p_3)
fmt.Println(p_4)
}
|
Output:
333
564592
656757686879
18
Example 2:
package main
import (
"fmt"
"sync/atomic"
)
type addr uintptr
func (p *addr) adds() uintptr {
return atomic.AddUintptr((*uintptr)(p), 32686776785)
}
func main() {
var p addr
for i := 4; i < 1000; i *= 5 {
fmt.Println(p.adds())
}
}
|
Output:
32686776785
65373553570
98060330355
130747107140
In the above example, we have defined a function adds that returns the output returned from calling AddUintptr method. In the main function, we have defined a “for” loop that will increment the value of ‘p’ in each call. Here, the second parameter of the AddUintptr() 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 AddUintptr() method in the next call until the loop stops.
Lets see how above example works:
1st parameter = 0, 2nd parameter = 32686776785 // returns (0 + 32686776785 = 32686776785)
// Now, the above output is 1st parameter
// in next call to AddUintptr() method
// It returns (32686776785 + 32686776785 = 65373553570)
1st parameter = 32686776785, 2nd parameter = 32686776785
// returns (65373553570 + 32686776785 = 130747107140) and so on
1st parameter = 65373553570, 2nd parameter = 32686776785
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...