亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

等待添加到緩沖通道的所有項目

等待添加到緩沖通道的所有項目

Go
嚕嚕噠 2022-06-06 17:42:30
我已經實現了 WaitGroup 但它沒有按預期工作,我需要打印所有 1000 條日志,但實際結果只是 ~9xx 日志,我知道根本原因是第一個 gorouting 尚未完成,而其余的 goroutines 在緩沖通道的循環已經完成我該如何解決這個問題?提前致謝package mainimport (    "log"    "sync")func main() {    buffer := make(chan int, 5)    var wg sync.WaitGroup    wg.Add(1)    go func(wg *sync.WaitGroup) {        for i := 1; i <= 1000; i++ {            buffer <- i        }        close(buffer)        wg.Done()    }(&wg)    for item := range buffer {        wg.Add(1)        go func(wg *sync.WaitGroup, item int) {            log.Printf("done for item %d\n", item)            wg.Done()        }(&wg, item)    }    wg.Wait()}更新我發現了問題,我在 GoLand IDE 中運行代碼并且它不會打印所有日志,如果我在終端中運行它應該沒問題
查看完整描述

2 回答

?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

但它已經在發生了。


由于它沒有正確訂購,我認為它會誤導你認為它只打印 ~9xx 日志。


我運行它并得到(未顯示完整輸出):


2020/06/03 10:38:35 done for item 986

2020/06/03 10:38:35 done for item 988

2020/06/03 10:38:35 done for item 1000

2020/06/03 10:38:35 done for item 995

2020/06/03 10:38:35 done for item 993

2020/06/03 10:38:35 done for item 996

2020/06/03 10:38:35 done for item 997

2020/06/03 10:38:35 done for item 991

2020/06/03 10:38:35 done for item 998

2020/06/03 10:38:35 done for item 990

2020/06/03 10:38:35 done for item 992

2020/06/03 10:38:35 done for item 999

2020/06/03 10:38:35 done for item 989

2020/06/03 10:38:35 done for item 412

注意:有 1000 個。


如果要確認:


go run main.go &> sample.txt // Redirects the output of the executable to sample.txt

cat sample.txt | wc -l       // Counts the number of lines in output

是1000。


查看完整回答
反對 回復 2022-06-06
?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

我沒有看到 waitgroup 有任何問題,它正在 go playground上打印所有 1000 條日志。



查看完整回答
反對 回復 2022-06-06
  • 2 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號