Home >Backend Development >Golang >How to Accurately Count Active Goroutines in a Concurrent Go Program?
How to Count and Display the Number of Active Goroutines
In your program, you want to monitor the count of currently active goroutines while concurrently dequeuing and enqueueing a queue. While you've provided code for managing your queue, you've inquired about a method to retrieve the current number of active goroutines.
Here's a revised version of your code using WaitGroup:
import ( "fmt" "sync" ) var element int func deen(wg *sync.WaitGroup, queue chan int) { for element := range queue { wg.Done() // Decrement the WaitGroup count upon completion fmt.Println("element is", element) if element%2 == 0 { fmt.Println("new element is", element) wg.Add(2) // Increment WaitGroup count for spawned goroutines 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 fmt.Println("initial active goroutines:", runtime.NumGoroutine()) for i := 0; i < 4; i++ { wg.Add(1) // Increment WaitGroup count for each spawned goroutine go deen(&wg, queue) } wg.Wait() // Wait for all goroutines to complete close(queue) fmt.Println("final active goroutines:", runtime.NumGoroutine()) fmt.Println("list length:", len(queue)) // Expect 0 }
The above is the detailed content of How to Accurately Count Active Goroutines in a Concurrent Go Program?. For more information, please follow other related articles on the PHP Chinese website!