atomic.LoadPointer() Function in Golang With Examples
Last Updated :
17 Jan, 2022
In Go language, atomic packages supply lower level atomic memory that is helpful is implementing synchronization algorithms. The LoadPointer() function in Go language is used to atomically load *addr. This function is defined under the atomic package. Here, you need to import “sync/atomic” and “unsafe” package in order to use these functions.
Syntax:
func LoadPointer(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 automatically loads *addr and returns unsafe.Pointer.
Example 1:
C
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))
px1 := (*L)(atomic.LoadPointer(unsafepL))
fmt.Println(px1 == &px)
fmt.Println(&px1)
}
|
Output:
true
0xc0000b8018 // Can be different at different run times
Here, the StorePointer method adds value to the *addr and then LoadPointer method atomically loads *addr. So, here loading is accomplished hence, true is returned and the value of unsafe.Pointer returned here can be different at different run times.
Example 2:
C
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
px1 := (*L)(atomic.LoadPointer(unsafepL))
fmt.Println(px1 == &px)
fmt.Println(&px1)
}
|
Output:
false
0xc00000e028 // A random value is returned in each run
Here, false is returned as here the unsafe.pointer is not stored before so, LoadPointer() method was not able to load the *addr. Moreover, the address value returned here is the address of px1.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...