atomic.AddUint32() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddUint32() 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 function. Syntax:
func AddUint32(addr *uint32, delta uint32) (new uint32)
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 AddUint32(&x, ^uint32(c-1)). And if you want to decrement x particularly, then it can be done by AddUint32(&x, ^uint32(0)). Note: (*uint32) is the pointer to a uint32 value. And uint32 is an unsigned integer type of bit size 32. Moreover, uint32 contains the set of all unsigned 32-bit integers from 0 to 4294967295. 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 uint32 = 45
j uint32 = 67
k uint32 = 4294967295
l uint32 = 0
z int = 5
)
const (
x uint32 = 6
y uint32 = 3
)
a_1 := atomic.AddUint32(&i, -uint32(z))
a_2 := atomic.AddUint32(&j, ^(y - 1))
a_3 := atomic.AddUint32(&k, x-1)
a_4 := atomic.AddUint32(&l, ^uint32(z-1))
fmt.Println(a_1)
fmt.Println(a_2)
fmt.Println(a_3)
fmt.Println(a_4)
}
|
Output:
40
64
4
4294967291
Example 2:
javascript
package main
import (
"fmt"
"sync/atomic"
)
type addr uint32
func (u *addr) add() uint32 {
return atomic.AddUint32((*uint32)(u), 4)
}
func main() {
var u addr
for i := 0; i < 17; i += 2 {
fmt.Println(u.add())
}
}
|
Output:
4
8
12
16
20
24
28
32
36
In the above example, we have defined a function add that returns the output returned from calling AddUint32 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 AddUint32() 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 AddUint32() method in the next call until the loop stops. Lets see how above example works:
1st parameter = 0, 2nd parameter = 4 // returns (0 + 4 = 4)
// Now, the above output is 1st parameter in next call to AddUint32() method
1st parameter = 4, 2nd parameter = 4 // returns (4 + 4 = 8)
1st parameter = 8, 2nd parameter = 4 // returns (8 + 4 = 12) and so on.
Last Updated :
27 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...