paraflou
paraflou

Reputation: 413

Merge maps in Golang concurrently

I am trying to merge many maps concurrently. I want to pop two maps from a channel, merge these two maps and send the merged map back to same channel until merging maps is finished.

The bigger picture is that I produce maps concurrently and I want to start merging maps as soon as there are two available. In the end I want to have one merged map of all produced maps.

I want to make sth like this:

func processMaps(c1 chan map[string]int) {
    for map1 := range c1 {
        map2 := <-c1
        mergedMap := mergeMaps(map1, map2)
        c1 <- mergedMap
        }
    }
}

Any ideas?

Upvotes: 0

Views: 1700

Answers (1)

Thundercat
Thundercat

Reputation: 120941

Start with an empty map and merge any maps received on the channel to the map:

merged := make(make[string]int)
for m := range c {
    for k, v := range m {
       merged[k] = v
    }
}

The loop exits when channel c is closed. The map merged is the merge of all maps received on c.

Use variable to refer to the merged map instead of sending the merged map back to the channel. Sending the merged map back to the channel makes the end condition more complicated without increasing concurrency.

Upvotes: 1

Related Questions