通过使用channel 限制goroutines数量
func TestLimitRoutines(t *testing.T) {
ch := make(chan bool, 4)
taskCnt := math.MaxInt
for i := 0; i < taskCnt; i++ {
ch <- true
go func(ch <-chan bool, num int) {
fmt.Println("go func ", i, " goroutine count = ", runtime.NumGoroutine())
<-ch
}(ch, i)
}
time.Sleep(time.Second * 10)
}
package test
import (
"fmt"
"math"
"runtime"
"sync"
"testing"
)
var wg sync.WaitGroup
func TestLimitRoutines(t *testing.T) {
ch := make(chan int)
for i := 0; i < 4; i++ {
go func(ch chan int) {
for task := range ch {
defer wg.Done()
fmt.Println(fmt.Sprintf("go func %d goroutine count = %d", task, runtime.NumGoroutine()))
}
}(ch)
}
for i := 0; i < math.MaxInt; i++ {
wg.Add(1)
ch <- i
}
wg.Wait()
}