在進行并發(fā)編程時,我們經(jīng)常遇到需要等待所有g(shù)oroutine完成后再繼續(xù)執(zhí)行的情況。在Go語言中,我們可以通過使用WaitGroup來實現(xiàn)這個目標。WaitGroup是一個計數(shù)信號量,可以用于等待一組goroutine的完成。在繼續(xù)之前,我們需要調(diào)用WaitGroup的Wait方法,這樣可以確保所有的goroutine都已經(jīng)完成了任務(wù)。在本文中,我們將介紹如何正確使用WaitGroup來管理goroutine的執(zhí)行順序。
問題內(nèi)容
我需要 golang 調(diào)度程序在繼續(xù)之前運行所有 goroutine,runtime.gosched() 無法解決。
問題在于 go 例程運行速度太快,以至于 start() 中的“select”在 stopstream() 內(nèi)的“select”之后運行,然后“case
運行此代碼https://go.dev/play/p/dq85xqju2q_z
很多時候你會看到這兩個回應(yīng)
未掛起時的預(yù)期響應(yīng):
2009/11/10 23:00:00 start 2009/11/10 23:00:00 receive chan 2009/11/10 23:00:03 end
登錄后復(fù)制
掛起時的預(yù)期響應(yīng),但掛起時的響應(yīng)卻不是那么快:
2009/11/10 23:00:00 start 2009/11/10 23:00:00 default 2009/11/10 23:00:01 timer 2009/11/10 23:00:04 end
登錄后復(fù)制
代碼
package main import ( "log" "runtime" "sync" "time" ) var wg sync.WaitGroup func main() { wg.Add(1) //run multiples routines on a huge system go start() wg.Wait() } func start() { log.Println("Start") chanStopStream := make(chan bool) go stopStream(chanStopStream) select { case <-chanStopStream: log.Println("receive chan") case <-time.After(time.Second): //if stopStream hangs do not wait more than 1 second log.Println("TIMER") //call some crash alert } time.Sleep(3 * time.Second) log.Println("end") wg.Done() } func stopStream(retChan chan bool) { //do some work that can be faster then caller or not runtime.Gosched() //time.Sleep(time.Microsecond) //better solution then runtime.Gosched() //time.Sleep(2 * time.Second) //simulate when this routine hangs more than 1 second select { case retChan <- true: default: //select/default is used because if the caller times out this routine will hangs forever log.Println("default") } }
登錄后復(fù)制
解決方法
在繼續(xù)執(zhí)行當(dāng)前 goroutine 之前,沒有辦法運行所有其他 goroutine。
通過確保 goroutine 不會在 stopstream
上阻塞來修復(fù)問題:
選項 1:將 chanstopstream
更改為緩沖通道。這確保了 stopstream
可以無阻塞地發(fā)送值。
func start() { log.println("start") chanstopstream := make(chan bool, 1) // <--- buffered channel go stopstream(chanstopstream) ... } func stopstream(retchan chan bool) { ... // always send. no select/default needed. retchan <- true }
登錄后復(fù)制
https://www.php.cn/link/56e48d306028f2a6c2ebf677f7e8f800
選項 2:關(guān)閉通道而不是發(fā)送值。通道始終可以由發(fā)送者關(guān)閉。在關(guān)閉的通道上接收返回通道值類型的零值。
func start() { log.Println("Start") chanStopStream := make(chan bool) // buffered channel not required go stopStream(chanStopStream) ... func stopStream(retChan chan bool) { ... close(retChan) }
登錄后復(fù)制
https://www.php.cn/link/a1aa0c486fb1a7ddd47003884e1fc67f