[Go] 利用有緩存channel控制同時併發的數量

若是有一個大循環,裏面每個都開啓groutine,那麼瞬間就會開啓很是多的groutine,要解決這個問題就要用channel的阻塞特性來解決spa

package main

import "time"

import "fmt"

func main() {
    control := make(chan interface{}, 2)
    for i := 1; i <= 10; i++ {
        control <- i //這裏應該放上面,若是放下面就會每次都執行三個了
        go func(j int) {
            fmt.Printf("go func: %d, time: %d\n", j, time.Now().Unix())
            time.Sleep(time.Second)
            <-control
        }(i)

    }
    //主groutine不要斷
    for {
        time.Sleep(time.Second)
    }
}
go func: 2, time: 1574427632
go func: 1, time: 1574427632
go func: 4, time: 1574427633
go func: 3, time: 1574427633
go func: 5, time: 1574427634
go func: 6, time: 1574427634
go func: 7, time: 1574427635
go func: 8, time: 1574427635
go func: 9, time: 1574427636
go func: 10, time: 1574427636

看時間每次只是同時執行兩個code

相關文章
相關標籤/搜索