Home > Backend Development > Golang > Is it safe to access different members of the same struct from concurrent goroutines in Go?

Is it safe to access different members of the same struct from concurrent goroutines in Go?

Susan Sarandon
Release: 2024-11-10 02:23:02
Original
523 people have browsed it

Is it safe to access different members of the same struct from concurrent goroutines in Go?

Thread Safety of Struct Member Access in Go

In Go, is it safe to access different members of the same struct from concurrent goroutines?

Consider this example:

package main

type Apple struct {
    color string
    size  uint
}

func main() {
    apple := &Apple{}
    go func() {
        apple.color = "red"
    }()
    go func() {
        apple.size = 42
    }()
}
Copy after login

Intuitively, this code appears safe as each goroutine modifies different struct members. However, the potential for thread safety issues extends beyond concurrent writes to the same variable.

It is indeed safe to access different struct members concurrently because each member represents a distinct variable. However, it is important to note that accessing struct members within a CPU cache line can incur performance penalties due to sequential memory access.

While Go ensures thread safety for different struct members, it does not guarantee it for pointer changes. Modifying the struct pointer concurrently could lead to unpredictable behavior. Therefore, it is crucial to avoid changing pointers to structs in concurrent goroutines.

The above is the detailed content of Is it safe to access different members of the same struct from concurrent goroutines in Go?. 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