Home > Backend Development > Golang > Is Pointer Assignment Atomic in Go, and How Can It Be Made Safe?

Is Pointer Assignment Atomic in Go, and How Can It Be Made Safe?

Linda Hamilton
Release: 2024-12-24 14:09:10
Original
329 people have browsed it

Is Pointer Assignment Atomic in Go, and How Can It Be Made Safe?

Assigning Pointers Atomically in Go

Go provides a variety of tools for managing concurrency, but one question that often arises is whether assigning a pointer is an atomic operation.

Atomic Operations in Go

In Go, the only operations that are guaranteed to be atomic are those found in the sync.atomic package. As such, assigning a pointer is not natively atomic.

Safe Pointer Assignment

To assign a pointer atomically, you have two options:

  1. Acquire a Lock: Using a lock (e.g., sync.Mutex) ensures that only one goroutine can access the pointer at a time, preventing race conditions.
  2. Use Atomic Primitives: The sync.atomic package offers atomic primitives like atomic.StorePointer and atomic.LoadPointer, which can be used to atomically assign and retrieve pointer values.

Example with Mutex

Here's an example using a sync.Mutex to protect a pointer assignment:

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

Example with Atomic Primitives

Alternatively, you can use atomic primitives to achieve atomicity:

import "sync/atomic"
import "unsafe"

type Struct struct {
    p unsafe.Pointer // some pointer
}

func main() {
    data := 1

    info := Struct{p: unsafe.Pointer(&data)}

    fmt.Printf("info is %d\n", *(*int)(info.p))

    otherData := 2

    atomic.StorePointer(&info.p, unsafe.Pointer(&otherData))

    fmt.Printf("info is %d\n", *(*int)(info.p))
}
Copy after login

Considerations

  • Using sync.atomic can complicate code due to the need to cast to unsafe.Pointer.
  • Locks are generally considered idiomatic in Go, while using atomic primitives is discouraged.
  • An alternative approach is to use a single goroutine for pointer access and communicate commands via channels, which aligns better with Go's concurrency model.

The above is the detailed content of Is Pointer Assignment Atomic in Go, and How Can It Be Made Safe?. 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