最近在使用goroutine同步数据,使用goroutine可以提升数据同步的速度。但在数据量较多的时候,不限制goroutine的数量会造成很大的内存开销,有可能会宕机。下面整理了几种可以控制goroutine 的方法。
1. 使用channel+waitgroup
package main
import (
"fmt"
"math"
"runtime"
"sync"
)
var wg = sync.WaitGroup{}
func main() {
total := math.MaxInt64
var wg sync.WaitGroup
ch := make(chan int, 10)
for i := 0; i < total; i++ {
num := i
ch <- 1
wg.Add(1)
go func(int) {
fmt.Println("go func", num, "goroutine count", runtime.NumGoroutine())
<-ch
wg.Done()
}(num)
}
wg.Wait()
}