以下go程序调试发现一个问题,求助

程序如下:可以完整运行
为什么

fmt.Println("运行的goruntine数量:" + getgoruntinesize())
这里打印的运行数量是2!? 应该是1啊,就一个主线程,其他的goruntine里,为什么有一个没有结束
package main

import (
    "bytes"
    "fmt"
    "github.com/gogf/gf/util/gconv"
    "github.com/gogf/gf/util/grand"
    "runtime"
    "runtime/pprof"
    "strconv"
    "sync"
    "time"
)

func main() {
    v := getnumber_5()
    fmt.Println("有goruntine获取到值:", v)

    time.Sleep(5 * time.Second)
    fmt.Println("运行的goruntine数量:" + getgoruntinesize())

    time.Sleep(10 * time.Second)
}

func getnumber_5() string {
    var wait = sync.WaitGroup{}
    wait.Add(1)
    infoback := make(chan string, 1)
    for i := 0; i < 20; i++ {
        go randomnum(infoback, &wait)
    }
    wait.Wait()
    close(infoback)
    temp := ""

    for v := range infoback {
        temp = v
    }
    return temp
}
func randomnum(info chan string, w *sync.WaitGroup) {

    {
    loop1:
        n := grand.N(1, 20)

        if n%2 == 0 {
            fmt.Println(GOID() + ":我满足条件了.. ")
            for {
                select {
                case <-info:
                    fmt.Println(GOID() + ":已经有其他 goruntine 完成了  监控到info被close")
                    return
                default:
                    info <- gconv.String(n)
                    w.Done()
                    return
                }
            }
        } else {
            goto loop1
        }
    }
}

func getgoruntinesize() string {
     
    var preback *pprof.Profile
    for _, p := range pprof.Profiles() {
        if p.Name() == "goroutine" {
            preback = p
            break
        }
         
    }
     
    return "正在运行中的goruntine数量: " + gconv.String(preback.Count())
}
func GOID() string {
    b := make([]byte, 64)
    b = b[:runtime.Stack(b, false)]
    b = bytes.TrimPrefix(b, []byte("goroutine "))
    b = b[:bytes.IndexByte(b, ' ')]
    n, _ := strconv.ParseUint(string(b), 10, 64)
    return gconv.String(n)
}
阅读 826
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题