Answer the question
In order to leave comments, you need to log in
How to concurrently write/read data in Go?
Good afternoon.
Who knows how to properly work with data structures in Go when they are accessed concurrently (read/write)?
I have been working with Go for several years, but there is still no clear understanding ...
I know about mutexes (sync.Mutex) and in trivial things, I seem to understand how to work safely, but what about this case?
type Child struct {
name string
}
type Parent struct {
mu sync.Mutex
Dict map[string]*Child
}
func (p *Parent) Add(child *Child) {
p.mu.Lock()
defer p.mu.Unlock()
p.Dict[child.name] = child
}
func (p *Parent) Export() (result map[string]Child) {
p.mu.Lock()
defer p.mu.Unlock()
for k, v := range p.Dict {
result[k] = *v
}
return result
}
Answer the question
In order to leave comments, you need to log in
1) You can. You don't modify map in any way.
2) Need to initialize map
func (p *Parent) Export() (result map[string]Child) {
result = make(map[string]Child)
p.mu.Lock()
defer p.mu.Unlock()
for k, v := range p.Dict {
result[k] = *v
}
return result
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question