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