atomic.AddInt32() Function in Golang With Examples
Last Updated :
30 Dec, 2020
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt32() function in Golang is used to atomically 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 AddInt32(addr *int32, delta int32) (new int32)
Here, addr indicates address and delta indicates a small number of bits greater than zero.
Note: (*int32) is the pointer to a int32 value. Moreover, int32 contains the set of all signed 32-bit integers from -2147483648 to 2147483647.
Return value: It adds addr and delta atomically and returns a new value.
Example 1:
Go
package main
import (
"fmt"
"sync/atomic"
)
func main() {
var (
i int32 = 97
j int32 = 48
k int32 = 34754567
l int32 = - 355363
)
const (
x int32 = 4
y int32 = 2
)
res_1 := atomic.AddInt32(&i, y)
res_2 := atomic.AddInt32(&j, y- 1 )
res_3 := atomic.AddInt32(&k, x- 1 )
res_4 := atomic.AddInt32(&l, x)
fmt.Println(res_1)
fmt.Println(res_2)
fmt.Println(res_3)
fmt.Println(res_4)
}
|
Output:
99
49
34754570
-355359
Example 2:
Go
package main
import (
"fmt"
"sync/atomic"
)
type addr int32
func (x *addr) add() int32 {
return atomic.AddInt32((* int32 )(x), 2 )
}
func main() {
var x addr
for i := 1 ; i < 7 ; i++ {
fmt.Println(x.add())
}
}
|
Output:
2
4
6
8
10
12
In the above example, we have defined a function add that returns the output returned from calling AddInt32 method. In the main function, we have defined a “for” loop that will increment the value of ‘x’ in each call. Here, the second parameter of the AddInt32() 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 AddInt32() method in the next call until the loop stops.
Lets see how above example works:
1st parameter = 0, 2nd parameter = 2 // returns ( 0 + 2 = 2)
// Now, the above output is 1st parameter in next call to AddInt32() method
1st parameter = 2, 2nd parameter = 2 // returns ( 2 + 2 = 4)
1st parameter = 4, 2nd parameter = 2 // returns ( 4 + 2 = 6) and so on.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...