lilydjwg / swapview-rosetta

Print swap usage per process. Implemented in various programming languages
491 stars 108 forks source link

[bug] Go_goroutine 版本 goroutine 同步问题 #122

Closed hmgle closed 7 years ago

hmgle commented 7 years ago

GetInfos() 函数返回前并没有等待 info_ch 里面的数据处理完:

    go func(info_ch chan *Info, list *[]Info) {
        for {
            tmp := <-info_ch
            if tmp != nil {
                *list = append(*list, *tmp)
            }
        }
    }(info_ch, &list)

我运行了该程序几次,大部分时候的结果都是漏加了数据。把上面的代码 sleep 一下,就 100% 重现了:

    go func(info_ch chan *Info, list *[]Info) {
        for {
            tmp := <-info_ch
            time.Sleep(time.Millisecond * 10)
            if tmp != nil {
                *list = append(*list, *tmp)
            }
        }
    }(info_ch, &list)

正确的做法要保证这个 goroutine 处理完数据该函数才返回。

lilydjwg commented 7 years ago

谢谢。这个重现率不是很高,以至于一直都没有发现……