這個問題在這里已經有了答案: golang sync.WaitGroup 永遠不會完成 3 個答案 將 sync.WaitGroup 與外部函式一起使用的最佳方式 2 個答案 GO - WaitGroups 參考中的指標或變數 1 個答案 Golang WaitGroup.Done() 被跳過 1 個回答 15 小時前關閉。
這是我的意思的一個簡單例子
package main
import (
"sync"
"testing"
"time"
)
func TestWaitGroup(t *testing.T) {
var wg sync.WaitGroup
quitSig := make(chan struct{})
go func(wg sync.WaitGroup, quitChan, chan struct{}) {
defer func() {
t.Log("Done...")
wg.Done()
t.Log("Done!")
}()
t.Log("waiting for quit channel signal...")
<-quitChan
t.Log("signal received")
}(wg, quitSig)
time.Sleep(5*time.Second)
t.Log("Done sleeping")
close(quitSig)
t.Log("closed quit signal channel")
wg.Wait()
t.Log("goroutine shutdown")
}
當我運行它時,我得到以下資訊
=== RUN TestWaitGroup
main.go:18: waiting for quit channel signal...
main.go:23: Done sleeping
main.go:25: closed quit signal channel
main.go:20: signal received
main.go:14: Done...
main.go:16: Done!
它只是掛在哪里,直到它超時。如果你只是做defer wg.Done()同樣的行為,就會被觀察到。我在跑步go1.18。這是一個錯誤還是我在這種情況下沒有正確使用 WaitGroups?
uj5u.com熱心網友回復:
兩個問題:
不要復制
sync.WaitGroup:來自檔案:A WaitGroup must not be copied after first use.
您需要
wg.Add(1)在開始作業之前 - 與wg.Done()
wg.Add(1) // <- add this
go func (wg *sync.WaitGroup ...) { // <- pointer
}(&wg, quitSig) // <- pointer to avoid WaitGroup copy
https://go.dev/play/p/UmeI3TdGvhg
uj5u.com熱心網友回復:
您正在傳遞等待組的副本,因此 goroutine 不會影響在外部范圍中宣告的等待組。通過以下方式修復它:
go func(wg *sync.WaitGroup, quitChan, chan struct{}) {
...
}(&wg, quitSig)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/457411.html
