Reading through a couple of lists I want to add all lines from each list into one big array. I run each list reader in it's own goroutine. Can I just append a line as soon as it's read?
Is this thread save or can this explode in my hand?
type listHolder {
entries []entry
}
func (h *listHolder) readAllLists(s []list) {
c := make(chan list)
var wg sync.WaitGroup
for _, l := range s {
wg.Add(1)
go h.readSomeList(&wg, l)
}
c.close()
wg.Wait()
}
func (h *listHolder) readSomeList(wg *sync.WaitGroup, l list) {
defer wg.Done()
for e := range extractEntry(l) {
h.entries = append(h.entries, newEntry(e))
}
}
Something like this would be ok. Or you might like to think up a different architecture, such as using a channel to feed the updates to a single go routine
type listHolder {
entries []entry
m sync.Mutex
}
func (h *listHolder) readAllLists(s []list) {
c := make(chan list)
var wg sync.WaitGroup
for _, l := range s {
wg.Add(1)
go h.readSomeList(&wg, l)
}
c.close()
wg.Wait()
}
func (h *listHolder) readSomeList(wg *sync.WaitGroup, l list) {
defer wg.Done()
for e := range extractEntry(l) {
h.m.Lock()
h.entries = append(h.entries, newEntry(e))
h.m.Unlock()
}
}