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 }() }
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!