R
R
Ruslan Yanberdin2018-06-05 16:42:19
go
Ruslan Yanberdin, 2018-06-05 16:42:19

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
}

Questions:
  1. Can I change the contents of the children without changing the pointer without a Parent lock?
  2. Export is needed to copy data, because it will take a long time to work with them. Did you copy it correctly?
  3. Are arguments in a function without a pointer copied?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Shoshin, 2018-06-05
@Duke565

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
}

3) Yes, they are copied.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question