Golang使用channel实现协程池限制最大协程数量

package main

import (
    "fmt"
    "strconv"
    "time"
    "sync"
)

var (
    maxRoutineNum = 3
)
type Duration int64
const (
    Nanosecond           = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

var wg sync.WaitGroup

func action(data string, ch chan int) {
    defer wg.Done()
    fmt.Println(data)
    time.Sleep(Second)
    <-ch
}

func main() {
    ch := make(chan int, maxRoutineNum)

    datas := [10]string{}
    for i := 0; i < 10; i++ {
        datas[i] = strconv.Itoa(i)
    }
    for i := 0; i < len(datas); i++ {
        ch <- 1
        wg.Add(1)
        go action(datas[i], ch)
    }

    // 休眠一下
    wg.Wait()
}
发布了226 篇原创文章 · 获赞 31 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/why444216978/article/details/104482680