count / display the number of active goroutines

不打扰是莪最后的温柔 提交于 2019-12-05 02:04:21

There's runtime.NumGoroutine but you're approaching this wrong.

  1. Your loops will keep spawning goroutines.
  2. this will unnecessarily burn cpu cycles because of the for loop.

One approach is to use a sync.WaitGroup.

func deen(wg *sync.WaitGroup, queue chan int) {
    for element := range queue {
        wg.Done()
        fmt.Println("element is ", element)
        if element%2 == 0 {
            fmt.Println("new element is ", element)
            wg.Add(2)
            queue <- (element*100 + 11)
            queue <- (element*100 + 33)
        }
    }
}

func main() {
    var wg sync.WaitGroup
    queue := make(chan int, 10)
    queue <- 1
    queue <- 2
    queue <- 3
    queue <- 0
    for i := 0; i < 4; i++ {
        wg.Add(1)
        go deen(&wg, queue)
    }
    wg.Wait()
    close(queue)
    fmt.Println("list is has len", len(queue)) //this must be 0
}

playground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!