Home >Backend Development >Golang >Is Atomic Pointer Assignment Possible in Go, and How Can It Be Achieved Safely?
Atomic Assignment of Pointers in Go
Is it possible to atomically assign a pointer in Golang? Specifically, if you want to set a pointer to nil and ensure other threads can immediately observe the change, is it necessary to use a lock?
In Java, the volatile keyword can be used to achieve atomic pointer assignment, but such a mechanism does not exist in Go.
Answer:
The only guaranteed atomic operations in Go are those provided by the sync.atomic package. Assigning a regular pointer is not inherently atomic.
To ensure atomicity, one option is to use a lock, such as sync.Mutex. Alternatively, you could consider using one of the sync.atomic primitives. However, the latter requires careful handling and may be difficult to implement correctly.
For example, consider the following idiomatic Go code:
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() }
These functions provide access to a pointer while maintaining thread safety through the use of a mutex.
Alternatively, if possible, it may be more idiomatic to limit pointer access to a single goroutine and use channels to communicate changes.
Using atomic.StorePointer
As an alternative to using locks, the sync/atomic package provides the StorePointer function for atomic pointer assignment. However, this approach requires the use of unsafe.Pointer and is not considered good practice due to its potential for errors and undefined behavior.
The above is the detailed content of Is Atomic Pointer Assignment Possible in Go, and How Can It Be Achieved Safely?. For more information, please follow other related articles on the PHP Chinese website!