Reputation: 787
I use 4 go routines to assign different member variables of a struct instance. Each member variable is only accessed by one go routine.
Do I need to add mutex when accessing the struct instance?
I am not sure if the 4 go routines access the same memory. I feel I should be cause all of them accesses the holder.
This code demonstrates what I'm doing.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
var res Response
var mu sync.Mutex
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
defer mu.Unlock()
res.A = []string{"a"}
}()
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
defer mu.Unlock()
res.B = "b"
}()
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
defer mu.Unlock()
res.C = 100
}()
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
defer mu.Unlock()
res.D = map[string]string{
"d": "dd",
}
}()
wg.Wait()
fmt.Println(res)
}
type Response struct {
A []string
B string
C int
D map[string]string
}
Upvotes: 0
Views: 374
Reputation: 186
You do not need a mutex for this program. As far as the Go memory model is concerned, separate fields of a struct are separate variables. Since the four goroutines are accessing four separate (sub-)variables, there is no data race, even without the mutex.
You can verify this by removing the mutex and running your program with the race detector enabled: https://golang.org/doc/articles/race_detector.html
Upvotes: 2