最近在使用goroutine同步数据,使用goroutine可以提升数据同步的速度。但在数据量较多的时候,不限制goroutine的数量会造成很大的内存开销,有可能会宕机。下面整理了几种可以控制goroutine 的方法。

1. 使用channel+waitgroup

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "runtime"
  6. "sync"
  7. )
  8. var wg = sync.WaitGroup{}
  9. func main() {
  10. total := math.MaxInt64
  11. var wg sync.WaitGroup
  12. ch := make(chan int, 10)
  13. for i := 0; i < total; i++ {
  14. num := i
  15. ch <- 1
  16. wg.Add(1)
  17. go func(int) {
  18. fmt.Println("go func", num, "goroutine count", runtime.NumGoroutine())
  19. <-ch
  20. wg.Done()
  21. }(num)
  22. }
  23. wg.Wait()
  24. }