使用select语句和带缓冲区的channel来控制函数并发执行次数
package main
import (
"fmt"
"time"
)
// cocurrency number of the do func
const cnum = 3
func main() {
var jobs = make(chan bool, cnum)
for {
for i := 0; i < 10; i++ {
go frqLimit(do, jobs, i)
}
time.Sleep(4e9)
}
}
func frqLimit(f func(), jobChan chan bool, i int) {
select {
case jobChan <- true:
f()
<-jobChan
default:
fmt.Println("job channel is full. pass ", i)
}
fmt.Println("jobs", i, "exit")
}
func do() {
time.Sleep(3e9)
fmt.Println("job done")
}