sync.WaitGroup 使用 Add(1)
、Done()
、Wait()
组合来实现多协程等待,如果某一协程未能合理处理错误,导致无法退出,此时需要引入超时机制。下面是一种超时处理方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wg := sync.WaitGroup{}
wg.Add(1)
done := make(chan struct{})
go func() {
wg.Wait()
done <- struct{}{}
}()
go func() {
time.Sleep(5 * time.Second)
wg.Done()
}()
timeout := time.Duration(10) * time.Second
fmt.Printf("Wait for waitgroup (up to %s)\n", timeout)
select {
case <-done:
fmt.Printf("Wait group finished\n")
case <-time.After(timeout):
fmt.Printf("Timed out waiting for wait group\n")
}
fmt.Printf("Free at last\n")
}
未超时,输出:
1
2
3
Wait for waitgroup (up to 10s)
Wait group finished
Free at last
修改 Sleep 时间
1
2
3
4
go func() {
time.Sleep(15 * time.Second)
wg.Done()
}()
超时输出:
1
2
3
Wait for waitgroup (up to 10s)
Timed out waiting for wait group
Free at last
本文网址: https://golangnote.com/topic/259.html 转摘请注明来源