登录
首页 >  Golang >  Go问答

count / 显示活跃的 goroutines 的数量

来源:Golang技术栈

时间:2023-03-23 09:14:45 127浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《count / 显示活跃的 goroutines 的数量》,主要内容是讲解golang等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我有一个队列和一个同时执行出队和入队的函数。我想确保在队列中运行正确数量的 goroutine,只要列表中有东西。

这是我正在使用的代码,但我想知道是否有办法打印当前活动的 goroutines 的数量

链接到游乐场

var element int

func deen(queue chan int) {

    element := 
<h2 class="daan">
    正确答案
</h2>
<p>有<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXpusdyfppZkr83GoZTZmpaup4SZcqK8q2mtyZBtYJGQaqSx3LSHmIlorcZne9qcu7apmtOFmqurfZ6ua4qcfn2gr7Oqu22CeYjesYiVzZHdrW6HqptkvIZ9Z76zhaqKjY-is9CzbQ' rel='nofollow'><code>runtime.NumGoroutine</code></a>,但你正在接近这个错误。</p>
<ol><li>你的循环将不断产生 goroutines。</li>
<li>由于 for 循环,这将不必要地消耗 CPU 周期。</li>
</ol><p>一种方法是使用sync.WaitGroup。</p>
<pre class="brush:go;toolbar:false">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 
<p><a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyerpd5r83Jh2bSmpXcoZrTk6XEZXqisWx5ppOzk3y4uMmvjmV8l8l7hs6B3LGjgZiCnLB2l6uzgI1lfoCKsbK3yqGNrICas3icmJK3sWyR4H2qvIaGnrOmhWU' rel='nofollow'><code>playground</code></a></p>
<p>---旧的越野车版本,里面有比赛---</p>
<pre class="brush:go;toolbar:false">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 
<p><a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXpusdyfr5Z5fZqwoZXamqqqrpLfZabFn5OqyHxxdH1pj6jK0L9slZ-Q362tfs6B3LKkkrqBZK92gqC0jYqbfaN-a77Qs7GDhp6as3uG3oaVsbOFmIVhu6yKnrSKdW0' rel='nofollow'><code>playground</code></a></p><p>本篇关于《count / 显示活跃的 goroutines 的数量》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!</p>
声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>