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
}