package main import ( "fmt" "maps" "slices" "strings" "sync" ) // tally counts words. It is safe to use from many goroutines at once. type tally struct { mu sync.Mutex // mu protects counts counts map[string]int } func newTally() *tally { return &tally{counts: map[string]int{}} } func (t *tally) add(word string) { t.mu.Lock() defer t.mu.Unlock() t.counts[word] = t.counts[word] + 1 } func (t *tally) snapshot() map[string]int { t.mu.Lock() defer t.mu.Unlock() return maps.Clone(t.counts) } func worker(documents <-chan string, words *tally) { for doc := range documents { for _, w := range strings.Fields(doc) { words.add(strings.ToLower(w)) } } } // wordCount is one row of the result. type wordCount struct { word string count int } // mostFirst puts the higher count first, and equal counts in word order. func mostFirst(a wordCount, b wordCount) int { if a.count != b.count { return b.count - a.count } return strings.Compare(a.word, b.word) } func main() { documents := []string{ "The cat sat on the mat", "The dog sat on the log", "A cat and a dog met on a mat", "The end", "The cat and the dog are friends now", } words := newTally() jobs := make(chan string) var wg sync.WaitGroup for range 3 { wg.Go(func() { worker(jobs, words) }) } for _, doc := range documents { jobs <- doc } close(jobs) wg.Wait() rows := []wordCount{} for w, n := range words.snapshot() { rows = append(rows, wordCount{word: w, count: n}) } slices.SortFunc(rows, mostFirst) for _, row := range rows[:5] { fmt.Printf("%-5s %d\n", row.word, row.count) } }