Home >Backend Development >Golang >How Can I Efficiently Count and Manage Active Goroutines in Go?

How Can I Efficiently Count and Manage Active Goroutines in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 07:09:13913browse

How Can I Efficiently Count and Manage Active Goroutines in Go?

Counting Active Goroutines

When managing multiple goroutines concurrently, it is often necessary to monitor the number of active ones. In Go, the native runtime.NumGoroutine() function provides this information.

Consider the following example:

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 has len", len(queue)) //this must be 0
}

While this code demonstrates the use of goroutines, it does not provide a way to count the number of active goroutines at any given time.

To address this, a more efficient approach is to utilize a sync.WaitGroup, which coordinates the completion of multiple 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 has len", len(queue)) //this must be 0

}

In this modified code, the sync.WaitGroup is used to track the number of active goroutines. Each goroutine decrements the counter upon completion, and the main goroutine waits until all goroutines have finished executing before proceeding.

By leveraging runtime.NumGoroutine() or the more efficient sync.WaitGroup, Go programmers can effectively monitor and manage the active goroutines in their applications.

The above is the detailed content of How Can I Efficiently Count and Manage Active Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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