使用channel控制并发个数

17 阅读1分钟
package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "time"
)

func main() {
    strArr := []string{"abc", "cde", "aabb", "love", "nba"}
    res := CountLetters(strArr, 2)
    fmt.Println(res)
}

type LetterFreq map[rune]int

func CountLetters(strArr []string, concurrency int) LetterFreq {
    res := make(LetterFreq)

    ch := make(chan struct{}, concurrency)
    defer close(ch)
    wg := sync.WaitGroup{}

    for i := 0; i < len(strArr); i++ {
        ch <- struct{}{}
        wg.Add(1)
        go func(index int) {
            defer wg.Done()
            defer func() { <-ch }()

            time.Sleep(1 * time.Second)
            fmt.Printf("do work %d %s\n", index, strArr[index])
        }(i)
    }
    wg.Wait()

    return res
}