GolangNote

Golang笔记

Golang sync.WaitGroup 的 Wait 超时处理

Permalink

sync.WaitGroup 使用 Add(1)Done()Wait()组合来实现多协程等待,如果某一协程未能合理处理错误,导致无法退出,此时需要引入超时机制。下面是一种超时处理方法。

Go:
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
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

Related articles

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Write a Comment to "Golang sync.WaitGroup 的 Wait 超时处理"

Submit Comment Login
Based on Golang + fastHTTP + youdb | go1.16 Processed in 0ms