golang 實(shí)現(xiàn) sync.WaitGroup wait() 方法 超時(shí) 自動(dòng)釋放
思路是把 wg.wait() 放到一個(gè)協(xié)程里,通過chan向外發(fā)送完成信號(hào)。 外層通過一個(gè)select超時(shí)結(jié)構(gòu)來控制最大超時(shí)時(shí)間。
func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
c := make(chan struct{})
go func() {
defer close(c)
wg.Wait()
}()
select {
case <-c:
return false // completed normally
case <-time.After(timeout):
return true // timed out
}
}
posted on 2023-03-19 14:55 ed557 閱讀(914) 評(píng)論(0) 收藏 舉報(bào)
浙公網(wǎng)安備 33010602011771號(hào)