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

Is Pointer Assignment in Go Atomic?

Patricia Arquette
Release: 2024-12-18 21:26:10
Original
618 people have browsed it

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()
}
Copy after login

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))
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template