In this article, we will explore the AddUint64 Function in sync/atomic package in Go in details, along with examples.
AddUint64 in sync/atomic package in Go performs an atomic addition operation on a given unsigned 64-bit integer (uint64
). The function signature is as follows:
Syntax:
func AddUint64(addr *uint64, delta uint64) (new uint64)
AddUint64
accepts two arguments:
addr
: A pointer to theuint64
value that you want to update atomically.delta
: Theuint64
value you want to add to the value ataddr
.
The function returns the new value after the addition is complete.
Using AddUint64 in Go
In concurrent programming, multiple goroutines may access and modify shared data simultaneously. This can lead to race conditions and incorrect results. The AddUint64
function ensures that the addition operation is performed atomically, preventing any data races or inconsistencies.
Here’s an example of how to use the AddUint64
function to safely increment a counter from multiple goroutines:
Example
package main
import (
"fmt"
"sync"
"sync/atomic"
)
var counter uint64
func main() {
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
defer wg.Done()
atomic.AddUint64(&counter, 1)
}()
}
wg.Wait()
fmt.Printf("Counter value: %d\n", counter)
}
In this example, we create a global counter
variable of type uint64
. Then, we launch 100 goroutines, each of which increments the counter by 1 using AddUint64
. The sync.WaitGroup
is used to ensure that the main goroutine waits for all the other goroutines to finish their execution.
After all goroutines have finished, the main goroutine prints the value of the counter. Since we used AddUint64
to update the counter atomically, we can be confident that the final value is correct and free of data races.
Conclusion
The AddUint64
function in the sync/atomic
package is a powerful tool for performing atomic addition operations on unsigned 64-bit integers in Go. By using this function, you can ensure that your concurrent programs are safe from race conditions and data inconsistencies. Make sure to explore other atomic operations provided by the sync/atomic
package to implement complex synchronization algorithms and develop efficient concurrent applications in Go.
To check more Go related articles. Pls click given below link:
https://techieindoor.com/go-net-package-in-go-golang/
https://pkg.go.dev/net/[email protected]