Home >Backend Development >Golang >Is Pointer Assignment in Go Atomic?

Is Pointer Assignment in Go Atomic?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 21:26:10692browse

Is Pointer Assignment in Go Atomic?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn