Golang 中的并发限制与超时控制

简介:

前言
上回在 用 Go 写一个轻量级的 ssh 批量操作工具 里提及过,我们做 Golang 并发的时候要对并发进行限制,对 goroutine 的执行要有超时控制。那会没有细说,这里展开讨论一下。

以下示例代码全部可以直接在 The Go Playground 上运行测试:

并发
我们先来跑一个简单的并发看看

 1package main
 2
 3import (
 4    "fmt"
 5    "time"
 6)
 7
 8func run(task_id, sleeptime int, ch chan string) {
 9
10    time.Sleep(time.Duration(sleeptime) * time.Second)
11    ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
12    return
13}
14
15func main() {
16    input := []int{3, 2, 1}
17    ch := make(chan string)
18    startTime := time.Now()
19    fmt.Println("Multirun start")
20    for i, sleeptime := range input {
21        go run(i, sleeptime, ch)
22    }
23
24    for range input {
25        fmt.Println(<-ch)
26    }
27
28    endTime := time.Now()
29    fmt.Printf("Multissh finished. Process time %s. Number of tasks is %d", endTime.Sub(startTime), len(input))
30}

函数 run() 接受输入的参数,sleep 若干秒。然后通过 go 关键字并发执行,通过 channel 返回结果。

channel 顾名思义,他就是 goroutine 之间通信的“管道"。管道中的数据流通,实际上是 goroutine 之间的一种内存共享。我们通过他可以在 goroutine 之间交互数据。

1ch <- xxx // 向 channel 写入数据
2<- ch // 从 channel 中读取数据

channel 分为无缓冲(unbuffered)和缓冲(buffered)两种。例如刚才我们通过如下方式创建了一个无缓冲的 channel。

1ch := make(chan string)

channel 的缓冲,我们一会再说,先看看刚才看看执行的结果。

1Multirun start
2task id 2 , sleep 1 second
3task id 1 , sleep 2 second
4task id 0 , sleep 3 second
5Multissh finished. Process time 3s. Number of tasks is 3
6Program exited.

三个 goroutine `分别 sleep 了 3,2,1秒。但总耗时只有 3 秒。所以并发生效了,go 的并发就是这么简单。

按序返回
刚才的示例中,我执行任务的顺序是 0,1,2。但是从 channel 中返回的顺序却是 2,1,0。这很好理解,因为 task 2 执行的最快嘛,所以先返回了进入了 channel,task 1 次之,task 0 最慢。

如果我们希望按照任务执行的顺序依次返回数据呢?可以通过一个 channel 数组(好吧,应该叫切片)来做,比如这样

1package main
 2
 3import (
 4    "fmt"
 5    "time"
 6)
 7
 8func run(task_id, sleeptime int, ch chan string) {
 9
10    time.Sleep(time.Duration(sleeptime) * time.Second)
11    ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
12    return
13}
14
15func main() {
16    input := []int{3, 2, 1}
17    chs := make([]chan string, len(input))
18    startTime := time.Now()
19    fmt.Println("Multirun start")
20    for i, sleeptime := range input {
21        chs[i] = make(chan string)
22        go run(i, sleeptime, chs[i])
23    }
24
25    for _, ch := range chs {
26        fmt.Println(<-ch)
27    }
28
29    endTime := time.Now()
30    fmt.Printf("Multissh finished. Process time %s. Number of tasks is %d", endTime.Sub(startTime), len(input))
31}

运行结果,现在输出的次序和输入的次序一致了。

1Multirun start
2task id 0 , sleep 3 second
3task id 1 , sleep 2 second
4task id 2 , sleep 1 second
5Multissh finished. Process time 3s. Number of tasks is 3
6Program exited.

超时控制
刚才的例子里我们没有考虑超时。然而如果某个 goroutine 运行时间太长了,那很肯定会拖累主 goroutine 被阻塞住,整个程序就挂起在那儿了。因此我们需要有超时的控制。

通常我们可以通过select + time.After 来进行超时检查,例如这样,我们增加一个函数 Run() ,在 Run() 中执行 go run() 。并通过 select + time.After 进行超时判断。

 1package main
 2
 3import (
 4    "fmt"
 5    "time"
 6)
 7
 8func Run(task_id, sleeptime, timeout int, ch chan string) {
 9    ch_run := make(chan string)
10    go run(task_id, sleeptime, ch_run)
11    select {
12    case re := <-ch_run:
13        ch <- re
14    case <-time.After(time.Duration(timeout) * time.Second):
15        re := fmt.Sprintf("task id %d , timeout", task_id)
16        ch <- re
17    }
18}
19
20func run(task_id, sleeptime int, ch chan string) {
21
22    time.Sleep(time.Duration(sleeptime) * time.Second)
23    ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
24    return
25}
26
27func main() {
28    input := []int{3, 2, 1}
29    timeout := 2
30    chs := make([]chan string, len(input))
31    startTime := time.Now()
32    fmt.Println("Multirun start")
33    for i, sleeptime := range input {
34        chs[i] = make(chan string)
35        go Run(i, sleeptime, timeout, chs[i])
36    }
37
38    for _, ch := range chs {
39        fmt.Println(<-ch)
40    }
41    endTime := time.Now()
42    fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input))
43}

运行结果,task 0 和 task 1 已然超时

1Multirun start
2task id 0 , timeout
3task id 1 , timeout
4tasi id 2 , sleep 1 second
5Multissh finished. Process time 2s. Number of task is 3
6Program exited.

并发限制
如果任务数量太多,不加以限制的并发开启 goroutine 的话,可能会过多的占用资源,服务器可能会爆炸。所以实际环境中并发限制也是一定要做的。

一种常见的做法就是利用 channel 的缓冲机制——开始的时候我们提到过的那个。

我们分别创建一个带缓冲和不带缓冲的 channel 看看

1ch := make(chan string) // 这是一个无缓冲的 channel,或者说缓冲区长度是 0
2ch := make(chan string, 1) // 这是一个带缓冲的 channel, 缓冲区长度是 1 

这两者的区别在于,如果 channel 没有缓冲,或者缓冲区满了。goroutine 会自动阻塞,直到 channel 里的数据被读走为止。举个例子

 1package main
 2
 3import (
 4    "fmt"
 5)
 6
 7func main() {
 8    ch := make(chan string)
 9    ch <- "123"
10    fmt.Println(<-ch)
11} 

这段代码执行将报错

1fatal error: all goroutines are asleep - deadlock!
2
3goroutine 1 [chan send]:
4main.main()
5    /tmp/sandbox531498664/main.go:9 +0x60
6
7Program exited.

这是因为我们创建的 ch 是一个无缓冲的 channel。因此在执行到 ch<-"123",这个 goroutine 就阻塞了,后面的 fmt.Println(<-ch) 没有办法得到执行。所以将会报 deadlock 错误。

如果我们改成这样,程序就可以执行

 1package main
 2
 3import (
 4    "fmt"
 5)
 6
 7func main() {
 8    ch := make(chan string, 1)
 9    ch <- "123"
10    fmt.Println(<-ch)
11}

执行

1123
2
3Program exited.

如果我们改成这样

 1package main
 2
 3import (
 4    "fmt"
 5)
 6
 7func main() {
 8    ch := make(chan string, 1)
 9    ch <- "123"
10    ch <- "123"
11    fmt.Println(<-ch)
12    fmt.Println(<-ch)
13}

尽管读取了两次 channel,但是程序还是会死锁,因为缓冲区满了,goroutine 阻塞挂起。第二个 ch<- "123" 是没有办法写入的。

1fatal error: all goroutines are asleep - deadlock!
2
3goroutine 1 [chan send]:
4main.main()
5    /tmp/sandbox642690323/main.go:10 +0x80
6
7Program exited.

因此,利用 channel 的缓冲设定,我们就可以来实现并发的限制。我们只要在执行并发的同时,往一个带有缓冲的 channel 里写入点东西(随便写啥,内容不重要)。让并发的 goroutine 在执行完成后把这个 channel 里的东西给读走。这样整个并发的数量就讲控制在这个 channel 的缓冲区大小上。

比如我们可以用一个 bool 类型的带缓冲 channel 作为并发限制的计数器。

1    chLimit := make(chan bool, 1)

然后在并发执行的地方,每创建一个新的 goroutine,都往 chLimit 里塞个东西。

1for i, sleeptime := range input {
2        chs[i] = make(chan string, 1)
3        chLimit <- true
4        go limitFunc(chLimit, chs[i], i, sleeptime, timeout)
5    }

这里通过 go 关键字并发执行的是新构造的函数。他在执行完原来的 Run() 后,会把 chLimit 的缓冲区里给消费掉一个。

1limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) {
2        Run(task_id, sleeptime, timeout, ch)
3        <-chLimit
4    }

这样一来,当创建的 goroutine 数量到达 chLimit 的缓冲区上限后。主 goroutine 就挂起阻塞了,直到这些 goroutine 执行完毕,消费掉了 chLimit 缓冲区中的数据,程序才会继续创建新的 goroutine。我们并发数量限制的目的也就达到了。

以下是完整代码

 1package main
 2
 3import (
 4    "fmt"
 5    "time"
 6)
 7
 8func Run(task_id, sleeptime, timeout int, ch chan string) {
 9    ch_run := make(chan string)
10    go run(task_id, sleeptime, ch_run)
11    select {
12    case re := <-ch_run:
13        ch <- re
14    case <-time.After(time.Duration(timeout) * time.Second):
15        re := fmt.Sprintf("task id %d , timeout", task_id)
16        ch <- re
17    }
18}
19
20func run(task_id, sleeptime int, ch chan string) {
21
22    time.Sleep(time.Duration(sleeptime) * time.Second)
23    ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
24    return
25}
26
27func main() {
28    input := []int{3, 2, 1}
29    timeout := 2
30    chLimit := make(chan bool, 1)
31    chs := make([]chan string, len(input))
32    limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) {
33        Run(task_id, sleeptime, timeout, ch)
34        <-chLimit
35    }
36    startTime := time.Now()
37    fmt.Println("Multirun start")
38    for i, sleeptime := range input {
39        chs[i] = make(chan string, 1)
40        chLimit <- true
41        go limitFunc(chLimit, chs[i], i, sleeptime, timeout)
42    }
43
44    for _, ch := range chs {
45        fmt.Println(<-ch)
46    }
47    endTime := time.Now()
48    fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input))
49}

运行结果

1Multirun start
2task id 0 , timeout
3task id 1 , timeout
4task id 2 , sleep 1 second
5Multissh finished. Process time 5s. Number of task is 3
6Program exited.

chLimit 的缓冲是 1。task 0 和 task 1 耗时 2 秒超时。task 2 耗时 1 秒。总耗时 5 秒。并发限制生效了。

如果我们修改并发限制为 2

1chLimit := make(chan bool, 2)

运行结果

1Multirun start
2task id 0 , timeout
3task id 1 , timeout
4task id 2 , sleep 1 second
5Multissh finished. Process time 3s. Number of task is 3
6Program exited.

task 0 , task 1 并发执行,耗时 2秒。task 2 耗时 1秒。总耗时 3 秒。符合预期。

有没有注意到代码里有个地方和之前不同。这里,用了一个带缓冲的 channel

1chs[i] = make(chan string, 1)

还记得上面的例子么。如果 channel 不带缓冲,那么直到他被消费掉之前,这个 goroutine 都会被阻塞挂起。
然而如果这里的并发限制,也就是 chLimit 生效阻塞了主 goroutine,那么后面消费这些数据的代码并不会执行到。。。于是就 deadlock 拉!

1  for _, ch := range chs {
2        fmt.Println(<-ch)
3    }

所以给他一个缓冲就好了。

参考文献
从Deadlock报错理解Go channel机制(一)
golang-what-is-channel-buffer-size
golang-using-timeouts-with-channels

原文发布时间为:2018-12-6

本文作者:Golang语言社区

本文来自云栖社区合作伙伴“Golang语言社区”,了解相关信息可以关注“Golangweb”微信公众号

相关文章
|
18天前
|
人工智能 Go 调度
掌握Go并发:Go语言并发编程深度解析
掌握Go并发:Go语言并发编程深度解析
|
18天前
|
安全 Java Go
Java vs. Go:并发之争
【4月更文挑战第20天】
22 1
|
13天前
|
SQL Go 数据库
【Go语言专栏】Go语言中的事务处理与并发控制
【4月更文挑战第30天】Go语言在数据库编程中支持事务处理和并发控制,确保ACID属性和多用户环境下的数据完整性。`database/sql`包提供事务管理,如示例所示,通过`Begin()`、`Commit()`和`Rollback()`执行和控制事务。并发控制利用Mutex、WaitGroup和Channel防止数据冲突。结合事务与并发控制,开发者可处理复杂场景,实现高效、可靠的数据库应用。
|
5天前
|
Go
深度探讨 Golang 中并发发送 HTTP 请求的最佳技术
深度探讨 Golang 中并发发送 HTTP 请求的最佳技术
|
7天前
|
Cloud Native Go 云计算
多范式编程语言Go:并发与静态类型的结合
Go语言是Google于2007年开发的开源编程语言,旨在提高程序开发和部署的效率。它的独特特征在于结合了并发处理与静态类型系统,提供了简洁、高效、并行处理能力的编程体验。本文将探讨Go语言的特点、应用场景以及其在现代软件开发中的优势。
|
10天前
|
安全 Go
Golang深入浅出之-Go语言中的并发安全队列:实现与应用
【5月更文挑战第3天】本文探讨了Go语言中的并发安全队列,它是构建高性能并发系统的基础。文章介绍了两种实现方法:1) 使用`sync.Mutex`保护的简单队列,通过加锁解锁确保数据一致性;2) 使用通道(Channel)实现无锁队列,天生并发安全。同时,文中列举了并发编程中常见的死锁、数据竞争和通道阻塞问题,并给出了避免这些问题的策略,如明确锁边界、使用带缓冲通道、优雅处理关闭以及利用Go标准库。
24 5
|
10天前
|
存储 缓存 安全
Golang深入浅出之-Go语言中的并发安全容器:sync.Map与sync.Pool
Go语言中的`sync.Map`和`sync.Pool`是并发安全的容器。`sync.Map`提供并发安全的键值对存储,适合快速读取和少写入的情况。注意不要直接遍历Map,应使用`Range`方法。`sync.Pool`是对象池,用于缓存可重用对象,减少内存分配。使用时需注意对象生命周期管理和容量控制。在多goroutine环境下,这两个容器能提高性能和稳定性,但需根据场景谨慎使用,避免不当操作导致的问题。
33 4
|
11天前
|
安全 Go 开发者
Golang深入浅出之-Go语言中的CSP模型:深入理解并发哲学
【5月更文挑战第2天】Go语言的并发编程基于CSP模型,强调通过通信共享内存。核心概念是goroutines(轻量级线程)和channels(用于goroutines间安全数据传输)。常见问题包括数据竞争、死锁和goroutine管理。避免策略包括使用同步原语、复用channel和控制并发。示例展示了如何使用channel和`sync.WaitGroup`避免死锁。理解并发原则和正确应用CSP模型是编写高效安全并发程序的关键。
31 4
|
11天前
|
安全 Go 开发者
Golang深入浅出之-Go语言中的CSP模型:深入理解并发哲学
【5月更文挑战第1天】Go语言基于CSP理论,借助goroutines和channels实现独特的并发模型。Goroutine是轻量级线程,通过`go`关键字启动,而channels提供安全的通信机制。文章讨论了数据竞争、死锁和goroutine泄漏等问题及其避免方法,并提供了一个生产者消费者模型的代码示例。理解CSP和妥善处理并发问题对于编写高效、可靠的Go程序至关重要。
23 2
|
11天前
|
设计模式 Go 调度
Golang深入浅出之-Go语言中的并发模式:Pipeline、Worker Pool等
【5月更文挑战第1天】Go语言并发模拟能力强大,Pipeline和Worker Pool是常用设计模式。Pipeline通过多阶段处理实现高效并行,常见问题包括数据竞争和死锁,可借助通道和`select`避免。Worker Pool控制并发数,防止资源消耗,需注意任务分配不均和goroutine泄露,使用缓冲通道和`sync.WaitGroup`解决。理解和实践这些模式是提升Go并发性能的关键。
29 2