Assigning Pointers Atomically in Go
Go provides a variety of tools for managing concurrency, but one question that often arises is whether assigning a pointer is an atomic operation.
Atomic Operations in Go
In Go, the only operations that are guaranteed to be atomic are those found in the sync.atomic package. As such, assigning a pointer is not natively atomic.
Safe Pointer Assignment
To assign a pointer atomically, you have two options:
Example with Mutex
Here's an example using a sync.Mutex to protect a pointer assignment:
import "sync" var secretPointer *int var pointerLock sync.Mutex func CurrentPointer() *int { pointerLock.Lock() defer pointerLock.Unlock() return secretPointer } func SetPointer(p *int) { pointerLock.Lock() secretPointer = p pointerLock.Unlock() }
Example with Atomic Primitives
Alternatively, you can use atomic primitives to achieve atomicity:
import "sync/atomic" import "unsafe" type Struct struct { p unsafe.Pointer // some pointer } func main() { data := 1 info := Struct{p: unsafe.Pointer(&data)} fmt.Printf("info is %d\n", *(*int)(info.p)) otherData := 2 atomic.StorePointer(&info.p, unsafe.Pointer(&otherData)) fmt.Printf("info is %d\n", *(*int)(info.p)) }
Considerations
The above is the detailed content of Is Pointer Assignment Atomic in Go, and How Can It Be Made Safe?. For more information, please follow other related articles on the PHP Chinese website!