In this article, we will explore the StorePointer() Function in sync/atomic package in Go in details, along with examples.
The StorePointer function in go is part of the “sync/atomic” package in Go, which provides low-level atomic memory operations. This function atomically sets the value of a pointer variable. It is a write operation that ensures the value written is immediately visible to other concurrent threads. The function signature is as follows:
Syntax:
func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)
The function takes a pointer to an unsafe.Pointer
variable addr
and an unsafe.Pointer
value val
as arguments. It sets the value of addr
to val
atomically.
Example
To illustrate the usage of the StorePointer function, let’s create a simple program simulating concurrent data access. We will create two goroutines: one that sets a shared flag pointer to a specific address using the StorePointer function and another that reads and prints the flag value using the atomic.LoadPointer function.
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
"unsafe"
)
func main() {
var flag *int
flags := []int{1, 2, 3, 4, 5}
var sharedFlag unsafe.Pointer
var wg sync.WaitGroup
// Writer goroutine
wg.Add(1)
go func() {
defer wg.Done()
for _, v := range flags {
atomic.StorePointer(&sharedFlag, unsafe.Pointer(&v))
fmt.Printf("Writer: Flag set to %d\n", v)
time.Sleep(time.Millisecond * 500)
}
}()
// Reader goroutine
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 10; i++ {
flag = (*int)(atomic.LoadPointer(&sharedFlag))
fmt.Printf("Reader: Current flag value is %d\n", *flag)
time.Sleep(time.Millisecond * 250)
}
}()
wg.Wait()
}
In this example, we use the sync.WaitGroup
to ensure that both goroutines complete before the program exits. The writer goroutine sets the sharedFlag
value using the atomic.StorePointer
function, ensuring atomicity. Meanwhile, the reader goroutine reads the sharedFlag
value using the atomic.LoadPointer
function, guaranteeing that it always reads the latest value written by the writer goroutine.
This example demonstrates how the StorePointer function can be used to perform atomic write operations on a shared pointer variable, ensuring data consistency across concurrent threads.
Conclusion
The StorePointer function is a critical utility provided by the sync/atomic package in Go, enabling atomic write operations on pointer variables. It is particularly useful in concurrent programming when multiple goroutines access shared memory. Using the StorePointer function ensures data consistency and helps eliminate race conditions, contributing to the overall stability and reliability of your concurrent Go applications.
To check more Go related articles. Pls click given below link:
https://www.techieindoor.com/go-storeint64-in-sync-atomic-package/
https://pkg.go.dev/net/[email protected]