In a scenario where you have a queue with concurrent operations, it becomes essential to monitor the number of active goroutines. This ensures that the appropriate number of goroutines are handling the queue, optimizing performance and resource utilization.
The provided code snippet demonstrates a loop that spawns goroutines based on the number of elements in a queue. However, this approach has several drawbacks:
A better solution is to utilize a synchronization mechanism. Here, a WaitGroup is employed:
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 len", len(queue)) //this must be 0 }
This revised code ensures that the number of goroutines is always limited to four, and it completes processing once all elements in the queue have been handled. This approach effectively addresses the problem of excessive goroutine creation and CPU consumption.
The above is the detailed content of How to Effectively Monitor and Control the Number of Active Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!