Go 限制goroutine

限制单位时间内的 goroutine 执行大小

package main

import (
    "fmt"
    "time"
)

// 限制单位时间内执行次数
func main() {
    limitChan := make(chan struct{})

    recoverChan := make(chan struct{})
    runOverChan := make(chan struct{})

    limitCount := 10
    nowCount := 0
    getTime := false

    go func() {
        for {
            if !getTime {
                nowCount++
                fmt.Println("do something", nowCount)
                if nowCount >= limitCount {
                    limitChan <- struct{}{}
                    getTime = true
                    <-recoverChan
                }
            }
        }
    }()

    for {
        select {
        case <-limitChan:
            nowCount = 0
            fmt.Println("get limit cmd")

        case <-time.After(time.Nanosecond):

            fmt.Println("time is over")
            // 防止死锁
            if getTime {
                recoverChan <- struct{}{}
                getTime = false
            }

        case <-runOverChan:
            break
        }
    }

}

改进版本 直接声明一个大小的变量 然后执行一次就减一次 直到 0

package main

import (
    "fmt"
    "time"
)

// 限制单位时间内执行次数
func main() {

    recoverChan := make(chan struct{})
    runOverChan := make(chan struct{})

    limitCount := 10

    go func() {
        for {
            select {

            case <-time.After(time.Second):
                fmt.Println("time is over")
                recoverChan <- struct{}{}
                limitCount = 10

            case <-runOverChan:
                break
            }
        }
    }()

    for i := 0; i < 10000; i++ {
        if limitCount > 0 {
            go func(limitCount int) {
                fmt.Println("do something", limitCount)
            }(limitCount)
        } else {
            <-recoverChan
        }
        limitCount--
    }

}

  • 简单的一个模版

你可能感兴趣的:(Go 限制goroutine)