Home > Backend Development > Golang > Is Atomic Pointer Assignment Possible in Go, and How Can It Be Achieved Safely?

Is Atomic Pointer Assignment Possible in Go, and How Can It Be Achieved Safely?

Mary-Kate Olsen
Release: 2024-12-12 11:08:10
Original
790 people have browsed it

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

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!

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