Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

concurrency - count / display the number of active goroutines

I have a queue and a function that does both dequeueing and enqueueing. I want to make sure that the right amount of goroutines operate on the queue, as long as there is something in the list.

This is the code I am using, but I was wondering if there is a way of printing the amount of currently active goroutines

Link to playground

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

}    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...