Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it thread safe to access different members of struct in go?

Tags:

Is it safe to access different struct members from different goroutines?

I understand that writing to the same variable without sync is dangareous:

package main  type Apple struct {     color string     size  uint }  func main() {     apple := &Apple{}     go func() {         apple.color = "red"     }()     go func() {         apple.color = "green"     }() } 

But can you write to different struct members without any kind of synchronization?

package main  type Apple struct {     color string     size  uint }  func main() {     apple := &Apple{}     go func() {         apple.color = "red"     }()     go func() {         apple.size = 42     }() } 

Or should I use chan or sync.Mutex for that?

like image 287
Kamil Dziedzic Avatar asked Apr 07 '15 16:04

Kamil Dziedzic


People also ask

Are Go structs thread-safe?

Go channels are great, but not always applicableIt's a data structure which enables one to achieve thread-safe code in a multi-threaded environment. It's nice because you don't need any synchronisation whatsoever as long as you use it to share data across threads.

Is struct thread-safe Swift?

Structs are thread-safe Since structs are unique copies, it's only possible for one thread at a time to manage them under most circumstances. This prevents them from being accessed by more than one thread simultaneously which can prevent difficult-to-track bugs.

What is Golang thread-safe?

It's used so that when one thread (or goroutine in the case of Golang) is accessing a value inside a memory address, it can lock out the other threads so they have to wait in line.

How do you define structs in Go?

Defining a struct typeThe type keyword introduces a new type. It is followed by the name of the type ( Person ) and the keyword struct to indicate that we're defining a struct . The struct contains a list of fields inside the curly braces. Each field has a name and a type.


1 Answers

It should be safe to access different variables from different threads, and struct members are different variables. So yes it should be safe.

However, it may not be fast. Variables that are close together in memory like struct members are will share a CPU cache line. A cache line is the smallest piece of memory that a CPU (well, most current models) can lock. That means that CPU-2 has to wait to write until CPU-1 has finished with that cache line even if they are writing to different variables.

It is NOT safe to change the pointer to the struct while writing to the struct from different threads. In your example if you had a third goroutine that did apple = &Apple{} some of the other goroutines in other threads might write to the old Apple or the new Apple and you wouldn't know.

like image 181
Zan Lynx Avatar answered Oct 18 '22 12:10

Zan Lynx