package main
import (
"sync"
"fmt"
)
var m = make(map[string]string)
var seen = make(map[string]bool)
func main() {
wg := new(sync.WaitGroup)
wg.Add(1)
ch := make(chan string)
go deduplicate(ch, wg)
toAdd := []string{"foo", "bar", "baz", "foo"}
for _, s := range toAdd {
ch <- s
}
wg.Wait()
fmt.Println(m)
}
func deduplicate(ch chan string, wg *sync.WaitGroup) {
for s := range ch {
if seen[s] {
wg.Done()
continue
}
seen[s] = true
go write(s)
}
}
func write(s string) {
m[s] = "written"
}
Is the code above safe to use? Note that multiple strings will be written to the map m
concurrently, but they are sure to be unique values, so no string will be written more than once.