Home > Backend Development > Golang > How Can I Accurately Count and Display the Number of Active Goroutines in My Go Program?

How Can I Accurately Count and Display the Number of Active Goroutines in My Go Program?

Barbara Streisand
Release: 2024-12-05 12:42:11
Original
977 people have browsed it

How Can I Accurately Count and Display the Number of Active Goroutines in My Go Program?

Count and Display the Number of Active Goroutines

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
}
Copy after login

In this revised code:

  • deen() now uses a sync.WaitGroup to signal when it has finished processing an element.
  • main() starts four goroutines and waits for them to complete.
  • The wg.Add() and wg.Done() calls ensure that main() waits for all goroutines to finish before proceeding.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template