Home > Backend Development > Golang > How to Accurately Count and Manage Active Goroutines in Go?

How to Accurately Count and Manage Active Goroutines in Go?

DDD
Release: 2024-11-28 18:21:11
Original
999 people have browsed it

How to Accurately Count and Manage Active Goroutines in Go?

How to Count and Display the Number of Active Goroutines

In this code, we have a queue and a function deen that performs both dequeueing and enqueueing:

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

However, there is no way to print the current number of active goroutines.

Using runtime.NumGoroutine

While there is a way to get the total number of active goroutines using runtime.NumGoroutine, it's not the best approach. This is because the loops will continue spawning goroutines, leading to unnecessary CPU consumption.

A Better Approach: Using a Sync.WaitGroup

A more efficient approach is to use a sync.WaitGroup, which lets us keep track of the number of active 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(&amp;wg, queue)
    }
    wg.Wait()
    close(queue)
    fmt.Println("list len", len(queue)) //this must be 0
}
Copy after login

Here, we start with four goroutines and wait until they finish their work before closing the queue. This approach provides a cleaner and more controlled way to manage the number of active goroutines.

The above is the detailed content of How to Accurately Count and Manage Active Goroutines in Go?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template