GolangNote

Golang笔记

Golang sync.WaitGroup 的 Wait 超时处理

Permalink

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

Go: WaitGroup 超时处理
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")
}

未超时,输出:

plaintext: 未超时输出
1
2
3
Wait for waitgroup (up to 10s)
Wait group finished
Free at last

修改 Sleep 时间

Go: 延迟响应
1
2
3
4
go func() {
    time.Sleep(15 * time.Second)
    wg.Done()
}()

超时输出:

plaintext: 超时输出
1
2
3
Wait for waitgroup (up to 10s)
Timed out waiting for wait group
Free at last

本文网址: https://golangnote.com/topic/259.html 转摘请注明来源

Related articles

golang共享数据用Mutex 或 Channel

在go 里,多线程对共享数据的操作一般要使用Mutex 或 Channel 来加锁或隔离通信。下面是一个使用Mutex 和 Channel 比较的例子。...

Golang 单实例实现网站多域名请求

有时候写网站,为了统一的后端,把不同业务都集中到一个后端,这时就需要处理多域名的请求,在 Go http server 里实现很简单,只需把不同域名映射到不同的 `http.Handler`。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 39ms