In this article, we will explore the AddUintptr Function in sync/atomic package in Go in details, along with examples.
AddUintptr is a function that atomically adds a value to a uintptr variable and returns the new value. The function signature is as follows:
Syntax:
func AddUintptr(addr *uintptr, delta uintptr) (new uintptr)
addr
: A pointer to the uintptr value that you want to add to.delta
: The uintptr value to be added to the value at addr.
The function returns the new value at addr after the addition is performed.
Example
In this example, we will use AddUintptr to atomically update the offset value of a buffer. This ensures that multiple goroutines can safely access and manipulate the buffer.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
const bufferSize = 100
type Buffer struct {
data [bufferSize]byte
offset uintptr
}
func (b *Buffer) Write(p []byte) (n int, err error) {
n = copy(b.data[b.offset:], p)
atomic.AddUintptr(&b.offset, uintptr(n))
return
}
func main() {
var buf Buffer
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
data := []byte("Hello, ")
n, _ := buf.Write(data)
fmt.Printf("Goroutine 1 wrote %d bytes\n", n)
}()
go func() {
defer wg.Done()
data := []byte("World!")
n, _ := buf.Write(data)
fmt.Printf("Goroutine 2 wrote %d bytes\n", n)
}()
wg.Wait()
fmt.Printf("Buffer content: %s\n", buf.data[:buf.offset])
}
In this example, we have a Buffer struct with a fixed-size byte array (data) and an offset value. The Write method of the Buffer struct appends data to the buffer and updates the offset atomically using AddUintptr. This ensures that multiple goroutines can safely write to the buffer without race conditions.
Output:
Goroutine 1 wrote 7 bytes
Goroutine 2 wrote 6 bytes
Buffer content: Hello, World!
Conclusion
The AddUintptr function in the sync/atomic package is an essential tool for managing shared resources in concurrent programming in Go. It enables you to atomically add a value to a uintptr variable, preventing race conditions and ensuring the integrity of your data. By understanding how to use AddUintptr and other atomic operations in the sync/atomic package, you can create more reliable and 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]