Atomicity of Pointer Assignments in Go
Is assigning a pointer in Go atomic? In other words, can multiple threads simultaneously manipulate a pointer without causing undefined behavior?
Answer:
Atomic operations in Go are limited to those explicitly defined in the sync.atomic package. Therefore, assigning a regular pointer is not guaranteed to be atomic.
To ensure consistent behavior across threads, you have two options:
1. Synchronization with Locks:
Use synchronization primitives like sync.Mutex to protect access to the pointer. For example:
var p *int var lock sync.Mutex func GetPointer() *int { lock.Lock() defer lock.Unlock() return p } func SetPointer(value *int) { lock.Lock() p = value lock.Unlock() }
2. Atomic Primitives (Caution Advised):
Alternatively, you can use sync.atomic to perform atomic pointer assignments. However, this approach requires careful handling of unsafe pointer conversions:
import ( "sync/atomic" "unsafe" ) var p = unsafe.Pointer(nil) func SetPointer(value *int) { atomic.StorePointer(&p, unsafe.Pointer(value)) }
Recommendation:
While atomic primitives provide a convenient way to perform atomic operations, they can be error-prone. Using mutexes is generally preferred in Go for protecting concurrent access to shared data.
The above is the detailed content of Is Pointer Assignment in Go Atomic?. For more information, please follow other related articles on the PHP Chinese website!