In this code, we have a queue and a function deen that performs both dequeueing and enqueueing:
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 }
However, there is no way to print the current number of active goroutines.
While there is a way to get the total number of active goroutines using runtime.NumGoroutine, it's not the best approach. This is because the loops will continue spawning goroutines, leading to unnecessary CPU consumption.
A more efficient approach is to use a sync.WaitGroup, which lets us keep track of the number of active goroutines.
func deen(wg *sync.WaitGroup, queue chan int) { for element := range queue { 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) } wg.Done() } } 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 len", len(queue)) //this must be 0 }
Here, we start with four goroutines and wait until they finish their work before closing the queue. This approach provides a cleaner and more controlled way to manage the number of active goroutines.
The above is the detailed content of How to Accurately Count and Manage Active Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!