package main import ( "fmt" "sync" "time" "unicode/utf8" ) // measure returns the number of letters in word, slowly. func measure(word string) int { time.Sleep(200 * time.Millisecond) return utf8.RuneCountInString(word) } // job is one word, with its place in the slice. type job struct { index int word string } // result is the length of the word at index. type result struct { index int length int } func worker(jobs <-chan job, results chan<- result) { for j := range jobs { results <- result{index: j.index, length: measure(j.word)} } } func main() { words := []string{ "goroutine", "channel", "mutex", "worker", "pool", "select", "context", "deadline", "ticker", "signal", } lengths := make([]int, len(words)) start := time.Now() jobs := make(chan job) results := make(chan result) var wg sync.WaitGroup for range 4 { wg.Go(func() { worker(jobs, results) }) } go func() { for i, w := range words { jobs <- job{index: i, word: w} } close(jobs) }() go func() { wg.Wait() close(results) }() for r := range results { lengths[r.index] = r.length } for i, w := range words { fmt.Printf("%-10s %d\n", w, lengths[i]) } fmt.Println("Took about", time.Since(start).Round(100*time.Millisecond)) }