atomic.StorePointer() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The StorePointer() function in Go language is used to atomically store val into *addr. This function is defined under the atomic package. Here, you need to import the “sync/atomic” package in order to use these functions.
Syntax:
func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)
Here, addr indicates address.
Note: (*unsafe.Pointer) is the pointer to a unsafe.Pointer value. And unsafe.Pointer type is helpful in enabling transitions between arbitrary types and builtin uintptr type. Moreover, unsafe is a package that is helpful in type safety of Go programs.
Return Value: It stores the val into *addr and then can be returned when required.
Example 1:
package main
import (
"fmt"
"sync/atomic"
"unsafe"
)
type L struct { x, y, z int }
var PL *L
func main() {
var unsafepL = (*unsafe.Pointer)(unsafe.Pointer(&PL))
var px L
atomic.StorePointer(
unsafepL, unsafe.Pointer(&px))
fmt.Println( "Val Stored!" )
}
|
Output:
Val Stored!
Here, the value unsafe.Pointer is stored in *addr that’s why above code returns the stated output.
Example 2:
package main
import (
"fmt"
"sync/atomic"
"unsafe"
)
type L struct { x, y, z int }
var PL *L
func main() {
var unsafepL = (*unsafe.Pointer)(unsafe.Pointer(&PL))
var px = 54634763
atomic.StorePointer(
unsafepL, unsafe.Pointer(&px))
fmt.Println(&px)
}
|
Output:
0xc0000b6010 // Can be different at different run times
Here, the stated unsafe.Pointer val is stored and the address of the stored val is returned here. Moreover, the address can be different at different run times.
Last Updated :
01 Apr, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...