计算/显示活动goroutines的数量

met*_*eto 12 concurrency go goroutine

我有一个队列和一个同时进行出列和排队的函数.我想确保在队列中运行适量的goroutine,只要列表中有东西.

这是我正在使用的代码,但我想知道是否有一种方法来打印当前活动的goroutines的数量

链接到游乐场

var element int

func deen(queue chan int) {

    element := <-queue
    fmt.Println("element is ", element)
    if element%2 == 0 {
        fmt.Println("new element is ", element)
        queue <- (element*100 + 11)
        queue <- (element*100 + 33)
    }
}

func main() {
    queue := make(chan int, 10)
    queue <- 1
    queue <- 2
    queue <- 3
    queue <- 0 
    for len(queue) != 0 {
        for i := 0; i < 2; i++ {
            go deen(queue)
        }
    }
    fmt.Scanln()
    fmt.Println("list is has len", len(queue)) //this must be 0

}    
Run Code Online (Sandbox Code Playgroud)

One*_*One 10

runtime.NumGoroutine,但你接近这个错误.

  1. 你的循环将继续产生goroutines.
  2. 由于for循环,这将不必要地烧掉cpu周期.

一种方法是使用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
}
Run Code Online (Sandbox Code Playgroud)

playground

  • @meto Goroutines不会那样死,如果goroutine死了,那么您的程序很可能崩溃了,我将添加一个示例。 (2认同)