You've created a function that dequeues and enqueues elements from a queue, ensuring that the correct number of goroutines operate on the queue as long as it contains elements. However, you desire a method to display the count of currently active goroutines.
runtime.NumGoroutine Usage
While the runtime.NumGoroutine function can provide the number of goroutines running in your program, it's crucial to approach the issue differently. This is because your loops will continuously spawn goroutines and waste CPU cycles due to the nested loop.
Alternative Approach: Sync.WaitGroup
A more effective solution is to utilize sync.WaitGroup. By modifying the code as follows:
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 }
In this revised code:
The above is the detailed content of How Can I Accurately Count and Display the Number of Active Goroutines in My Go Program?. For more information, please follow other related articles on the PHP Chinese website!